3 /* xbt_os_thread -- portability layer over the pthread API */
4 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD */
5 /* in SG, when using CONTEXT_UCONTEXT, xbt_os_thread_stub is used instead */
7 /* Copyright 2006,2007 Malek Cherier, Martin Quinson
8 * All right reserved. */
10 /* This program is free software; you can redistribute it and/or modify it
11 * under the terms of the license (GNU LGPL) which comes with this package. */
13 #include "xbt/sysdep.h"
15 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
17 #include "xbt/xbt_os_time.h" /* Portable time facilities */
18 #include "xbt/xbt_os_thread.h" /* This module */
19 #include "xbt_modinter.h" /* Initialization/finalization of this module */
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os,xbt,"Synchronization mechanism (OS-level)");
23 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
28 typedef struct xbt_os_thread_ {
32 pvoid_f_pvoid_t *start_routine;
35 static xbt_os_thread_t main_thread = NULL;
37 /* thread-specific data containing the xbt_os_thread_t structure */
38 static pthread_key_t xbt_self_thread_key;
39 static int thread_mod_inited = 0;
41 /* frees the xbt_os_thread_t corresponding to the current thread */
42 static void xbt_os_thread_free_thread_data(void*d){
46 /* callback: context fetching */
47 static ex_ctx_t *_os_thread_ex_ctx(void) {
48 return xbt_os_thread_self()->exception;
51 /* callback: termination */
52 static void _os_thread_ex_terminate(xbt_ex_t * e) {
56 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
59 void xbt_os_thread_mod_init(void) {
62 if (thread_mod_inited)
65 if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL)))
66 THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key");
68 main_thread=xbt_new(s_xbt_os_thread_t,1);
69 main_thread->name = (char*)"main";
70 main_thread->start_routine = NULL;
71 main_thread->param = NULL;
72 main_thread->exception = xbt_new(ex_ctx_t, 1);
73 XBT_CTX_INITIALIZE(main_thread->exception);
75 __xbt_ex_ctx = _os_thread_ex_ctx;
76 __xbt_ex_terminate = _os_thread_ex_terminate;
78 thread_mod_inited = 1;
80 void xbt_os_thread_mod_exit(void) {
81 /* FIXME: don't try to free our key on shutdown.
82 Valgrind detects no leak if we don't, and whine if we try to */
85 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
86 // THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
89 static void * wrapper_start_routine(void *s) {
90 xbt_os_thread_t t = s;
93 if ((errcode=pthread_setspecific(xbt_self_thread_key,t)))
94 THROW0(system_error,errcode,
95 "pthread_setspecific failed for xbt_self_thread_key");
96 return t->start_routine(t->param);
98 xbt_os_thread_t xbt_os_thread_create(const char*name,
99 pvoid_f_pvoid_t start_routine,
103 xbt_os_thread_t res_thread=xbt_new(s_xbt_os_thread_t,1);
104 res_thread->name = xbt_strdup(name);
105 res_thread->start_routine = start_routine;
106 res_thread->param = param;
107 res_thread->exception = xbt_new(ex_ctx_t, 1);
108 XBT_CTX_INITIALIZE(res_thread->exception);
110 if ((errcode = pthread_create(&(res_thread->t), NULL,
111 wrapper_start_routine, res_thread)))
112 THROW1(system_error,errcode,
113 "pthread_create failed: %s",strerror(errcode));
118 const char* xbt_os_thread_name(xbt_os_thread_t t) {
122 const char* xbt_os_thread_self_name(void) {
123 xbt_os_thread_t self = xbt_os_thread_self();
124 return self?self->name:"main";
127 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
131 if ((errcode = pthread_join(thread->t,thread_return)))
132 THROW1(system_error,errcode, "pthread_join failed: %s",
134 if (thread->exception)
135 free(thread->exception);
137 if (thread == main_thread) /* just killed main thread */
143 void xbt_os_thread_exit(int *retval) {
144 pthread_exit(retval);
147 xbt_os_thread_t xbt_os_thread_self(void) {
150 if (!thread_mod_inited)
153 res = pthread_getspecific(xbt_self_thread_key);
161 void xbt_os_thread_yield(void) {
164 void xbt_os_thread_cancel(xbt_os_thread_t t) {
165 pthread_cancel(t->t);
167 /****** mutex related functions ******/
168 typedef struct xbt_os_mutex_ {
169 /* KEEP IT IN SYNC WITH xbt_thread.c */
173 xbt_os_mutex_t xbt_os_mutex_init(void) {
174 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
177 if ((errcode = pthread_mutex_init(&(res->m),NULL)))
178 THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",
184 void xbt_os_mutex_lock(xbt_os_mutex_t mutex) {
187 if ((errcode=pthread_mutex_lock(&(mutex->m))))
188 THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s",
189 mutex, strerror(errcode));
192 void xbt_os_mutex_unlock(xbt_os_mutex_t mutex) {
195 if ((errcode=pthread_mutex_unlock(&(mutex->m))))
196 THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s",
197 mutex, strerror(errcode));
200 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
205 if ((errcode=pthread_mutex_destroy(&(mutex->m))))
206 THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s",
207 mutex, strerror(errcode));
211 /***** condition related functions *****/
212 typedef struct xbt_os_cond_ {
213 /* KEEP IT IN SYNC WITH xbt_thread.c */
217 xbt_os_cond_t xbt_os_cond_init(void) {
218 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t,1);
220 if ((errcode=pthread_cond_init(&(res->c),NULL)))
221 THROW1(system_error,errcode,"pthread_cond_init() failed: %s",
227 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
229 if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m))))
230 THROW3(system_error,errcode,"pthread_cond_wait(%p,%p) failed: %s",
231 cond,mutex, strerror(errcode));
236 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
238 struct timespec ts_end;
239 double end = delay + xbt_os_time();
240 ts_end.tv_sec = (time_t) floor(end);
241 ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000);
242 DEBUG3("pthread_cond_timedwait(%p,%p,%p)",&(cond->c),&(mutex->m), &ts_end);
243 switch ( (errcode=pthread_cond_timedwait(&(cond->c),&(mutex->m), &ts_end)) ) {
245 THROW3(timeout_error,errcode,"condition %p (mutex %p) wasn't signaled before timeout (%f)",
248 THROW4(system_error,errcode,"pthread_cond_timedwait(%p,%p,%f) failed: %s",
249 cond,mutex, delay, strerror(errcode));
253 void xbt_os_cond_signal(xbt_os_cond_t cond) {
255 if ((errcode=pthread_cond_signal(&(cond->c))))
256 THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s",
257 cond, strerror(errcode));
260 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
262 if ((errcode=pthread_cond_broadcast(&(cond->c))))
263 THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s",
264 cond, strerror(errcode));
266 void xbt_os_cond_destroy(xbt_os_cond_t cond){
271 if ((errcode=pthread_cond_destroy(&(cond->c))))
272 THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s",
273 cond, strerror(errcode));
277 void *xbt_os_thread_getparam(void) {
278 xbt_os_thread_t t = xbt_os_thread_self();
279 return t?t->param:NULL;
282 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
286 typedef struct xbt_os_thread_ {
288 HANDLE handle; /* the win thread handle */
289 unsigned long id; /* the win thread id */
290 pvoid_f_pvoid_t *start_routine;
292 } s_xbt_os_thread_t ;
294 /* key to the TLS containing the xbt_os_thread_t structure */
295 static unsigned long xbt_self_thread_key;
297 void xbt_os_thread_mod_init(void) {
298 xbt_self_thread_key = TlsAlloc();
300 void xbt_os_thread_mod_exit(void) {
302 if (!TlsFree(xbt_self_thread_key))
303 THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
306 static DWORD WINAPI wrapper_start_routine(void *s) {
307 xbt_os_thread_t t = (xbt_os_thread_t)s;
309 if(!TlsSetValue(xbt_self_thread_key,t))
310 THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
312 return (DWORD)t->start_routine(t->param);
316 xbt_os_thread_t xbt_os_thread_create(const char *name,pvoid_f_pvoid_t start_routine,
319 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1);
321 t->name = xbt_strdup(name);
322 t->start_routine = start_routine ;
325 t->handle = CreateThread(NULL,0,
326 (LPTHREAD_START_ROUTINE)wrapper_start_routine,
331 THROW0(system_error,(int)GetLastError(),"CreateThread failed");
337 const char* xbt_os_thread_name(xbt_os_thread_t t) {
341 const char* xbt_os_thread_self_name(void) {
342 xbt_os_thread_t t = xbt_os_thread_self();
343 return t?t->name:"main";
347 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
349 if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))
350 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
354 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
355 THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
358 CloseHandle(thread->handle);
363 void xbt_os_thread_exit(int *retval) {
370 xbt_os_thread_t xbt_os_thread_self(void) {
371 return TlsGetValue(xbt_self_thread_key);
374 void *xbt_os_thread_getparam(void) {
375 xbt_os_thread_t t = xbt_os_thread_self();
380 void xbt_os_thread_yield(void) {
383 void xbt_os_thread_cancel(xbt_os_thread_t t) {
387 /****** mutex related functions ******/
388 typedef struct xbt_os_mutex_ {
389 /* KEEP IT IN SYNC WITH xbt_thread.c */
390 CRITICAL_SECTION lock;
393 xbt_os_mutex_t xbt_os_mutex_init(void) {
394 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
396 /* initialize the critical section object */
397 InitializeCriticalSection(&(res->lock));
402 void xbt_os_mutex_lock(xbt_os_mutex_t mutex) {
404 EnterCriticalSection(& mutex->lock);
407 void xbt_os_mutex_unlock(xbt_os_mutex_t mutex) {
409 LeaveCriticalSection (& mutex->lock);
413 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
417 DeleteCriticalSection(& mutex->lock);
421 /***** condition related functions *****/
422 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
428 typedef struct xbt_os_cond_ {
429 /* KEEP IT IN SYNC WITH xbt_thread.c */
430 HANDLE events[MAX_EVENTS];
432 unsigned int waiters_count; /* the number of waiters */
433 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
436 xbt_os_cond_t xbt_os_cond_init(void) {
438 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1);
440 memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
442 /* initialize the critical section object */
443 InitializeCriticalSection(& res->waiters_count_lock);
445 res->waiters_count = 0;
447 /* Create an auto-reset event */
448 res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL);
450 if(!res->events[SIGNAL]){
451 DeleteCriticalSection(& res->waiters_count_lock);
453 THROW0(system_error,0,"CreateEvent failed for the signals");
456 /* Create a manual-reset event. */
457 res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
459 if(!res->events[BROADCAST]){
461 DeleteCriticalSection(& res->waiters_count_lock);
462 CloseHandle(res->events[SIGNAL]);
464 THROW0(system_error,0,"CreateEvent failed for the broadcasts");
470 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
472 unsigned long wait_result;
475 /* lock the threads counter and increment it */
476 EnterCriticalSection (& cond->waiters_count_lock);
477 cond->waiters_count++;
478 LeaveCriticalSection (& cond->waiters_count_lock);
480 /* unlock the mutex associate with the condition */
481 LeaveCriticalSection (& mutex->lock);
483 /* wait for a signal (broadcast or no) */
484 wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
486 if(wait_result == WAIT_FAILED)
487 THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
489 /* we have a signal lock the condition */
490 EnterCriticalSection (& cond->waiters_count_lock);
491 cond->waiters_count--;
493 /* it's the last waiter or it's a broadcast ? */
494 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
496 LeaveCriticalSection (& cond->waiters_count_lock);
498 /* yes it's the last waiter or it's a broadcast
499 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
503 if(!ResetEvent (cond->events[BROADCAST]))
504 THROW0(system_error,0,"ResetEvent failed");
506 /* relock the mutex associated with the condition in accordance with the posix thread specification */
507 EnterCriticalSection (& mutex->lock);
509 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
513 void xbt_os_cond_signal(xbt_os_cond_t cond) {
516 EnterCriticalSection (& cond->waiters_count_lock);
517 have_waiters = cond->waiters_count > 0;
518 LeaveCriticalSection (& cond->waiters_count_lock);
521 if(!SetEvent(cond->events[SIGNAL]))
522 THROW0(system_error,0,"SetEvent failed");
524 xbt_os_thread_yield();
527 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
530 EnterCriticalSection (& cond->waiters_count_lock);
531 have_waiters = cond->waiters_count > 0;
532 LeaveCriticalSection (& cond->waiters_count_lock);
535 SetEvent(cond->events[BROADCAST]);
538 void xbt_os_cond_destroy(xbt_os_cond_t cond){
543 if(!CloseHandle(cond->events[SIGNAL]))
546 if(!CloseHandle(cond->events[BROADCAST]))
549 DeleteCriticalSection(& cond->waiters_count_lock);
554 THROW0(system_error,0,"Error while destroying the condition");