]> mj.ucw.cz Git - libucw.git/blob - lib/threads.c
Free thread context structure on thread termination.
[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 struct ucwlib_context *
35 ucwlib_thread_context(void)
36 {
37   struct ucwlib_context *c = pthread_getspecific(ucwlib_context_key);
38   if (!c)
39     {
40       c = xmalloc_zero(sizeof(*c));
41       pthread_setspecific(ucwlib_context_key, c);
42     }
43   return c;
44 }
45
46 void
47 ucwlib_lock(void)
48 {
49   pthread_mutex_lock(&ucwlib_master_mutex);
50 }
51
52 void
53 ucwlib_unlock(void)
54 {
55   pthread_mutex_unlock(&ucwlib_master_mutex);
56 }
57
58 #else
59
60 struct ucwlib_context *
61 ucw_thread_context(void)
62 {
63   static struct ucwlib_context ucwlib_context;
64   return &ucwlib_context;
65 }
66
67 void
68 ucwlib_lock(void)
69 {
70 }
71
72 void
73 ucwlib_unlock(void)
74 {
75 }
76
77 #endif
78
79 #ifdef TEST
80
81 int main(void)
82 {
83   ucwlib_lock();
84   ucwlib_unlock();
85   ucwlib_thread_context();
86   return 0;
87 }
88
89 #endif