]> mj.ucw.cz Git - libucw.git/blob - lib/threads.c
Cleaned up insallation of library API.
[libucw.git] / lib / threads.c
1 /*
2  *      The UCW Library -- Threading Helpers
3  *
4  *      (c) 2006 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11 #include "lib/threads.h"
12
13 #ifdef CONFIG_UCW_THREADS
14
15 #include <pthread.h>
16
17 static pthread_key_t ucwlib_context_key;
18 static pthread_mutex_t ucwlib_master_mutex;
19
20 static void
21 ucwlib_free_thread_context(void *p)
22 {
23   xfree(p);
24 }
25
26 static void CONSTRUCTOR
27 ucwlib_threads_init(void)
28 {
29   if (pthread_key_create(&ucwlib_context_key, ucwlib_free_thread_context) < 0)
30     die("Cannot create pthread_key: %m");
31   pthread_mutex_init(&ucwlib_master_mutex, NULL);
32 }
33
34 static int
35 ucwlib_tid(void)
36 {
37   static int tid_counter;
38
39   ucwlib_lock();
40   int tid = ++tid_counter;
41   ucwlib_unlock();
42   return tid;
43 }
44
45 struct ucwlib_context *
46 ucwlib_thread_context(void)
47 {
48   struct ucwlib_context *c = pthread_getspecific(ucwlib_context_key);
49   if (!c)
50     {
51       c = xmalloc_zero(sizeof(*c));
52       c->thread_id = ucwlib_tid();
53       pthread_setspecific(ucwlib_context_key, c);
54     }
55   return c;
56 }
57
58 void
59 ucwlib_lock(void)
60 {
61   pthread_mutex_lock(&ucwlib_master_mutex);
62 }
63
64 void
65 ucwlib_unlock(void)
66 {
67   pthread_mutex_unlock(&ucwlib_master_mutex);
68 }
69
70 #else
71
72 struct ucwlib_context *
73 ucwlib_thread_context(void)
74 {
75   static struct ucwlib_context ucwlib_context;
76   return &ucwlib_context;
77 }
78
79 void
80 ucwlib_lock(void)
81 {
82 }
83
84 void
85 ucwlib_unlock(void)
86 {
87 }
88
89 #endif
90
91 #ifdef TEST
92
93 int main(void)
94 {
95   ucwlib_lock();
96   ucwlib_unlock();
97   log(L_INFO, "tid=%d", ucwlib_thread_context()->thread_id);
98   return 0;
99 }
100
101 #endif