]> pd.if.org Git - nbds/blob - runtime/runtime.c
fix compiler warnings/error under gcc 4.1 and 4.2
[nbds] / runtime / runtime.c
1 /* 
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  */
5 #define _POSIX_C_SOURCE 1 // for rand_r()
6 #include <stdlib.h>
7 #include <pthread.h>
8 #include "common.h"
9 #include "runtime.h"
10 #include "rlocal.h"
11 #include "mem.h"
12 #include "tls.h"
13
14 DECLARE_THREAD_LOCAL(tid_, int);
15 DECLARE_THREAD_LOCAL(rand_seed_, unsigned);
16
17 typedef struct thread_info {
18     int thread_id;
19     void *(*start_routine)(void *);
20     void *restrict arg;
21 } thread_info_t;
22
23 __attribute__ ((constructor)) void nbd_init (void) {
24     //sranddev();
25     INIT_THREAD_LOCAL(rand_seed_);
26     INIT_THREAD_LOCAL(tid_);
27     SET_THREAD_LOCAL(tid_, 0);
28     mem_init();
29     lwt_thread_init(0);
30     rcu_thread_init(0);
31 }
32
33 static void *worker (void *arg) {
34     thread_info_t *ti = (thread_info_t *)arg;
35     SET_THREAD_LOCAL(tid_, ti->thread_id);
36     LOCALIZE_THREAD_LOCAL(tid_, int);
37     SET_THREAD_LOCAL(rand_seed_, tid_+1);
38     lwt_thread_init(ti->thread_id);
39     rcu_thread_init(ti->thread_id);
40     void *ret = ti->start_routine(ti->arg);
41     nbd_free(ti);
42     return ret;
43 }
44
45 int nbd_thread_create (pthread_t *restrict thread, int thread_id, void *(*start_routine)(void *), void *restrict arg) {
46     thread_info_t *ti = (thread_info_t *)nbd_malloc(sizeof(thread_info_t));
47     ti->thread_id = thread_id;
48     ti->start_routine = start_routine;
49     ti->arg = arg;
50     return pthread_create(thread, NULL, worker, ti);
51 }
52
53 int nbd_rand (void) {
54     LOCALIZE_THREAD_LOCAL(rand_seed_, unsigned);
55     unsigned r = rand_r(&rand_seed_);
56     SET_THREAD_LOCAL(rand_seed_, r);
57     return r;
58 }