]> pd.if.org Git - nbds/blob - runtime/runtime.c
improve memory allocator
[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(102))) void nbd_init (void) {
24     //sranddev();
25     INIT_THREAD_LOCAL(rand_seed_);
26     INIT_THREAD_LOCAL(tid_);
27     SET_THREAD_LOCAL(tid_, 0);
28     lwt_thread_init(0);
29     rcu_thread_init(0);
30 }
31
32 static void *worker (void *arg) {
33     thread_info_t *ti = (thread_info_t *)arg;
34     SET_THREAD_LOCAL(tid_, ti->thread_id);
35     LOCALIZE_THREAD_LOCAL(tid_, int);
36     SET_THREAD_LOCAL(rand_seed_, tid_+1);
37     lwt_thread_init(ti->thread_id);
38     rcu_thread_init(ti->thread_id);
39     void *ret = ti->start_routine(ti->arg);
40     nbd_free(ti);
41     return ret;
42 }
43
44 int nbd_thread_create (pthread_t *restrict thread, int thread_id, void *(*start_routine)(void *), void *restrict arg) {
45     thread_info_t *ti = (thread_info_t *)nbd_malloc(sizeof(thread_info_t));
46     ti->thread_id = thread_id;
47     ti->start_routine = start_routine;
48     ti->arg = arg;
49     return pthread_create(thread, NULL, worker, ti);
50 }
51
52 int nbd_rand (void) {
53     LOCALIZE_THREAD_LOCAL(rand_seed_, unsigned);
54     unsigned r = rand_r(&rand_seed_);
55     SET_THREAD_LOCAL(rand_seed_, r);
56     return r;
57 }