]> mj.ucw.cz Git - libucw.git/blob - lib/threads.c
Added threading infrastructure to libucw and CONFIG_UCW_THREADS.
[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 CONSTRUCTOR
21 ucwlib_threads_init(void)
22 {
23   if (pthread_key_create(&ucwlib_context_key, NULL) < 0)
24     die("Cannot create pthread_key: %m");
25   pthread_mutex_init(&ucwlib_master_mutex, NULL);
26 }
27
28 struct ucwlib_context *
29 ucwlib_thread_context(void)
30 {
31   struct ucwlib_context *c = pthread_getspecific(ucwlib_context_key);
32   if (!c)
33     {
34       c = xmalloc_zero(sizeof(*c));
35       pthread_setspecific(ucwlib_context_key, c);
36     }
37   return c;
38 }
39
40 void
41 ucwlib_lock(void)
42 {
43   pthread_mutex_lock(&ucwlib_master_mutex);
44 }
45
46 void
47 ucwlib_unlock(void)
48 {
49   pthread_mutex_unlock(&ucwlib_master_mutex);
50 }
51
52 #else
53
54 struct ucwlib_context *
55 ucw_thread_context(void)
56 {
57   static struct ucwlib_context ucwlib_context;
58   return &ucwlib_context;
59 }
60
61 void
62 ucwlib_lock(void)
63 {
64 }
65
66 void
67 ucwlib_unlock(void)
68 {
69 }
70
71 #endif
72
73 #ifdef TEST
74
75 int main(void)
76 {
77   ucwlib_lock();
78   ucwlib_unlock();
79   ucwlib_thread_context();
80   return 0;
81 }
82
83 #endif