]> pd.if.org Git - nbds/blob - include/tls.h
work in progress
[nbds] / include / tls.h
1 /* 
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  *
5  * A platform independant wrapper around thread-local storage. On platforms that don't support 
6  * __thread variables (e.g. Mac OS X), we have to use the pthreads library for thread-local storage 
7  */
8 #ifndef TLS_H
9 #define TLS_H
10
11 #ifdef __ELF__ // use gcc thread-local storage (i.e. __thread variables)
12 #define DECLARE_THREAD_LOCAL(name, type) __thread type name
13 #define INIT_THREAD_LOCAL(name) 
14 #define SET_THREAD_LOCAL(name, value) name = value
15 #define LOCALIZE_THREAD_LOCAL(name, type)
16
17 #else//!__ELF__
18
19 #include <pthread.h>
20
21 #define DECLARE_THREAD_LOCAL(name, type) pthread_key_t name##_KEY
22
23 #define INIT_THREAD_LOCAL(name) \
24     do { \
25         if (pthread_key_create(&name##_KEY, NULL) != 0) { \
26             assert("error initializing thread local variable " #name, FALSE); \
27         } \
28     } while (0)
29
30 #define SET_THREAD_LOCAL(name, value) \
31     do { \
32         name = value; \
33         pthread_setspecific(name##_KEY, (void *)(size_t)value); \
34     } while (0);
35
36 #define LOCALIZE_THREAD_LOCAL(name, type) type name = (type)(size_t)pthread_getspecific(name##_KEY)
37
38 #endif//__ELF__
39 #endif//TLS_H