Added SILC Tls API for Thread-local storage. Added SilcTls
[silc.git] / lib / silcutil / win32 / silcwin32thread.c
1 /*
2
3   silcwin32thread.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2001 - 2007 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /* $Id$ */
20
21 #include "silc.h"
22
23 /**************************** SILC Thread API *******************************/
24
25 #ifdef SILC_THREADS
26
27 /* Thread structure for WIN32 */
28 typedef struct {
29   HANDLE thread;
30   SilcThreadStart start_func;
31   void *context;
32   SilcBool waitable;
33 } *SilcWin32Thread;
34
35 /* Actual routine that is called by WIN32 when the thread is created.
36    We will call the start_func from here. When this returns the thread
37    is destroyed. */
38
39 unsigned __stdcall silc_thread_win32_start(void *context)
40 {
41   SilcWin32Thread thread = (SilcWin32Thread)context;
42   SilcTls tls;
43
44   tls = silc_thread_tls_init();
45   if (tls)
46     tls->platform_context = thread;
47
48   silc_thread_exit(thread->start_func(thread->context));
49
50   silc_free(tls);
51
52   return 0;
53 }
54 #endif
55
56 SilcThread silc_thread_create(SilcThreadStart start_func, void *context,
57                               SilcBool waitable)
58 {
59 #ifdef SILC_THREADS
60   SilcWin32Thread thread;
61   unsigned id;
62
63   SILC_LOG_DEBUG(("Creating new thread"));
64
65   thread = silc_calloc(1, sizeof(*thread));
66   if (!thread)
67     return NULL;
68   thread->start_func = start_func;
69   thread->context = context;
70   thread->waitable = waitable;
71   thread->thread =
72     _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE)silc_thread_win32_start,
73                    (void *)thread, 0, &id);
74
75   if (!thread->thread) {
76     SILC_LOG_ERROR(("Could not create new thread"));
77     silc_free(thread);
78     return NULL;
79   }
80
81   return (SilcThread)thread;
82 #else
83   /* Call thread callback immediately */
84   (*start_func)(context);
85   return NULL;
86 #endif
87 }
88
89 void silc_thread_exit(void *exit_value)
90 {
91 #ifdef SILC_THREADS
92   SilcTls tls = silc_thread_get_tls();
93   SilcWin32Thread thread = tls->platform_context;
94
95   if (thread) {
96     /* If the thread is waitable the memory is freed only in silc_thread_wait
97        by another thread. If not waitable, free it now. */
98     if (!thread->waitable)
99       silc_free(thread);
100   }
101
102   _endthreadex(0);
103 #endif
104 }
105
106 SilcThread silc_thread_self(void)
107 {
108 #ifdef SILC_THREADS
109   SilcTls tls = silc_thread_get_tls();
110   SilcWin32Thread self = tls->platform_context;
111
112   if (!self) {
113     /* This should only happen for the main thread. */
114     HANDLE handle = GetCurrentThread ();
115     HANDLE process = GetCurrentProcess ();
116     self = silc_calloc(1, sizeof(*self));
117     if (self) {
118       DuplicateHandle(process, handle, process,
119                       &self->thread, 0, FALSE,
120                       DUPLICATE_SAME_ACCESS);
121       tls->platform_context = self;
122     }
123   }
124
125   return (SilcThread)self;
126 #else
127   return NULL;
128 #endif
129 }
130
131 SilcBool silc_thread_wait(SilcThread thread, void **exit_value)
132 {
133 #ifdef SILC_THREADS
134   SilcWin32Thread self = (SilcWin32Thread)thread;
135
136   SILC_LOG_DEBUG(("Waiting for thread %p", self));
137
138   if (!self->waitable)
139     return FALSE;
140
141   /* The thread is waitable thus we will free all memory after the
142      WaitForSingleObject returns, the thread is destroyed after that. */
143   WaitForSingleObject(self->thread, INFINITE);
144   CloseHandle(self->thread);
145
146   if (exit_value)
147     *exit_value = NULL;
148
149   return TRUE;
150 #else
151   return FALSE;
152 #endif
153 }
154
155 void silc_thread_yield(void)
156 {
157 #ifdef SILC_THREADS
158   SleepEx (0,0);
159 #endif /* SILC_THREADS */
160 }
161
162
163 /***************************** SILC Mutex API *******************************/
164
165 /* SILC Mutex structure */
166 struct SilcMutexStruct {
167 #ifdef SILC_THREADS
168   CRITICAL_SECTION mutex;
169 #endif /* SILC_THREADS */
170   unsigned int locked : 1;
171 };
172
173 SilcBool silc_mutex_alloc(SilcMutex *mutex)
174 {
175 #ifdef SILC_THREADS
176   *mutex = silc_calloc(1, sizeof(**mutex));
177   if (!(*mutex))
178     return FALSE;
179   InitializeCriticalSection(&((*mutex)->mutex));
180   return TRUE;
181 #else
182   return FALSE;
183 #endif /* SILC_THREADS */
184 }
185
186 void silc_mutex_free(SilcMutex mutex)
187 {
188 #ifdef SILC_THREADS
189   if (mutex) {
190     DeleteCriticalSection(&mutex->mutex);
191     silc_free(mutex);
192   }
193 #endif /* SILC_THREADS */
194 }
195
196 void silc_mutex_lock(SilcMutex mutex)
197 {
198 #ifdef SILC_THREADS
199   if (mutex) {
200     EnterCriticalSection(&mutex->mutex);
201     SILC_ASSERT(mutex->locked == FALSE);
202     mutex->locked = TRUE;
203   }
204 #endif /* SILC_THREADS */
205 }
206
207 void silc_mutex_unlock(SilcMutex mutex)
208 {
209 #ifdef SILC_THREADS
210   if (mutex) {
211     SILC_ASSERT(mutex->locked == TRUE);
212     mutex->locked = FALSE;
213     LeaveCriticalSection(&mutex->mutex);
214   }
215 #endif /* SILC_THREADS */
216 }
217
218 void silc_mutex_assert_locked(SilcMutex mutex)
219 {
220 #ifdef SILC_THREADS
221   if (mutex)
222     SILC_ASSERT(mutex->locked);
223 #endif /* SILC_THREADS */
224 }
225
226
227 /***************************** SILC Rwlock API ******************************/
228
229 /* SILC read/write lock structure */
230 struct SilcRwLockStruct {
231 #ifdef SILC_THREADS
232   SilcMutex mutex;
233   SilcCond cond;
234 #endif /* SILC_THREADS */
235   unsigned int readers : 31;
236   unsigned int locked  : 1;
237 };
238
239 SilcBool silc_rwlock_alloc(SilcRwLock *rwlock)
240 {
241 #ifdef SILC_THREADS
242   *rwlock = silc_calloc(1, sizeof(**rwlock));
243   if (!(*rwlock))
244     return FALSE;
245   if (!silc_mutex_alloc(&(*rwlock)->mutex)) {
246     silc_free(*rwlock);
247     return FALSE;
248   }
249   if (!silc_cond_alloc(&(*rwlock)->cond)) {
250     silc_mutex_free((*rwlock)->mutex);
251     silc_free(*rwlock);
252     return FALSE;
253   }
254   return TRUE;
255 #else
256   return FALSE;
257 #endif /* SILC_THREADS */
258 }
259
260 void silc_rwlock_free(SilcRwLock rwlock)
261 {
262 #ifdef SILC_THREADS
263   if (rwlock) {
264     silc_mutex_free(rwlock->mutex);
265     silc_cond_free(rwlock->cond);
266     silc_free(rwlock);
267   }
268 #endif /* SILC_THREADS */
269 }
270
271 void silc_rwlock_rdlock(SilcRwLock rwlock)
272 {
273 #ifdef SILC_THREADS
274   if (rwlock) {
275     silc_mutex_lock(rwlock->mutex);
276     rwlock->readers++;
277     silc_mutex_unlock(rwlock->mutex);
278   }
279 #endif /* SILC_THREADS */
280 }
281
282 void silc_rwlock_wrlock(SilcRwLock rwlock)
283 {
284 #ifdef SILC_THREADS
285   if (rwlock) {
286     silc_mutex_lock(rwlock->mutex);
287     while (rwlock->readers > 0)
288       silc_cond_wait(rwlock->cond, rwlock->mutex);
289     rwlock->locked = TRUE;
290   }
291 #endif /* SILC_THREADS */
292 }
293
294 void silc_rwlock_unlock(SilcRwLock rwlock)
295 {
296 #ifdef SILC_THREADS
297   if (rwlock) {
298     if (rwlock->locked) {
299       /* Unlock writer */
300       rwlock->locked = FALSE;
301       silc_mutex_unlock(rwlock->mutex);
302       return;
303     }
304
305     /* Unlock reader */
306     silc_mutex_lock(rwlock->mutex);
307     rwlock->readers--;
308     silc_cond_broadcast(rwlock->cond);
309     silc_mutex_unlock(rwlock->mutex);
310   }
311 #endif /* SILC_THREADS */
312 }
313
314
315 /**************************** SILC Cond API ******************************/
316
317 /* SILC Conditional Variable context */
318 struct SilcCondStruct {
319 #ifdef SILC_THREADS
320   HANDLE event;
321 #endif /* SILC_THREADS*/
322   unsigned int waiters : 23;
323   unsigned int signal  : 1;
324 };
325
326 SilcBool silc_cond_alloc(SilcCond *cond)
327 {
328 #ifdef SILC_THREADS
329   *cond = silc_calloc(1, sizeof(**cond));
330   if (*cond == NULL)
331     return FALSE;
332   (*cond)->event = CreateEvent(NULL, TRUE, FALSE, NULL);
333   return TRUE;
334 #else
335   return FALSE;
336 #endif /* SILC_THREADS*/
337 }
338
339 void silc_cond_free(SilcCond cond)
340 {
341 #ifdef SILC_THREADS
342   CloseHandle(cond->event);
343   silc_free(cond);
344 #endif /* SILC_THREADS*/
345 }
346
347 void silc_cond_signal(SilcCond cond)
348 {
349 #ifdef SILC_THREADS
350   cond->signal = TRUE;
351   SetEvent(cond->event);
352 #endif /* SILC_THREADS*/
353 }
354
355 void silc_cond_broadcast(SilcCond cond)
356 {
357 #ifdef SILC_THREADS
358   cond->signal = TRUE;
359   SetEvent(cond->event);
360 #endif /* SILC_THREADS*/
361 }
362
363 void silc_cond_wait(SilcCond cond, SilcMutex mutex)
364 {
365 #ifdef SILC_THREADS
366   silc_cond_timedwait(cond, mutex, 0);
367 #endif /* SILC_THREADS*/
368 }
369
370 SilcBool silc_cond_timedwait(SilcCond cond, SilcMutex mutex,
371                              int timeout)
372 {
373 #ifdef SILC_THREADS
374   DWORD ret, t = INFINITE;
375
376   if (timeout)
377     t = timeout;
378
379   while (TRUE) {
380     cond->waiters++;
381     silc_mutex_unlock(mutex);
382
383     ret = WaitForSingleObject(cond->event, t);
384
385     silc_mutex_lock(mutex);
386     cond->waiters--;
387
388     if (ret != WAIT_OBJECT_0)
389       return FALSE;
390
391     if (cond->signal) {
392       cond->signal = FALSE;
393       ResetEvent(cond->event);
394       break;
395     }
396   }
397 #endif /* SILC_THREADS*/
398   return TRUE;
399 }
400
401 /************************** Thread-local Storage ****************************/
402
403 #ifdef SILC_THREADS
404
405 static DWORD silc_tls;
406 SilcBool silc_tls_set = FALSE;
407
408 SilcTls silc_thread_tls_init(void)
409 {
410   SilcTls tls;
411
412   if (!silc_tls_set) {
413     silc_tls = TlsAlloc();
414     if (silc_tls == TLS_OUT_OF_INDEXES) {
415       SILC_LOG_ERROR(("Error creating Thread-local storage"));
416       return NULL;
417     }
418
419     silc_tls_set = TRUE;
420   }
421
422   if (silc_thread_get_tls())
423     return silc_thread_get_tls();
424
425   /* Allocate Tls for the thread */
426   tls = silc_calloc(1, sizeof(*tls));
427   if (!tls) {
428     SILC_LOG_ERROR(("Error allocating Thread-local storage"));
429     return NULL;
430   }
431
432   TlsSetValue(silc_tls, tls);
433   return tls;
434 }
435
436 SilcTls silc_thread_get_tls(void)
437 {
438   return (SilcTls)TlsGetValue(silc_tls);
439 }
440
441 #else
442
443 SilcTlsStruct tls;
444 SilcTls tls_ptr = NULL;
445
446 SilcTls silc_thread_tls_init(void)
447 {
448   if (silc_thread_get_tls())
449     return silc_thread_get_tls();
450
451   tls_ptr = &tls;
452   memset(tls_ptr, 0, sizeof(*tls_ptr));
453   return tls_ptr;
454 }
455
456 SilcTls silc_thread_get_tls(void)
457 {
458   return tls_ptr;
459 }
460
461 #endif /* SILC_THREADS */