1 /* xbt_os_thread -- portability layer over the pthread API */
2 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD */
3 /* in SG, when using CONTEXT_UCONTEXT, xbt_os_thread_stub is used instead */
5 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
6 * All rights reserved. */
8 /* This program is free software; you can redistribute it and/or modify it
9 * under the terms of the license (GNU LGPL) which comes with this package. */
11 #include "gras_config.h"
12 #include "xbt/sysdep.h"
14 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
16 #include "xbt/xbt_os_time.h" /* Portable time facilities */
17 #include "xbt/xbt_os_thread.h" /* This module */
18 #include "xbt_modinter.h" /* Initialization/finalization of this module */
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
21 "Synchronization mechanism (OS-level)");
23 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
27 #include <semaphore.h>
29 #ifdef HAVE_MUTEX_TIMEDLOCK
30 /* redefine the function header since we fail to get this from system headers on amd (at least) */
31 int pthread_mutex_timedlock(pthread_mutex_t * mutex,
32 const struct timespec *abs_timeout);
36 /* use named sempahore when sem_init() does not work */
38 static int next_sem_ID = 0;
39 static xbt_os_mutex_t next_sem_ID_lock;
42 typedef struct xbt_os_thread_ {
47 pvoid_f_pvoid_t start_routine;
48 xbt_running_ctx_t *running_ctx;
51 static xbt_os_thread_t main_thread = NULL;
53 /* thread-specific data containing the xbt_os_thread_t structure */
54 static pthread_key_t xbt_self_thread_key;
55 static int thread_mod_inited = 0;
57 /* frees the xbt_os_thread_t corresponding to the current thread */
58 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
60 if (thread == main_thread) /* just killed main thread */
63 free(thread->running_ctx);
68 /* callback: context fetching */
69 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
71 return xbt_os_thread_self()->running_ctx;
74 /* callback: termination */
75 static void _os_thread_ex_terminate(xbt_ex_t * e)
80 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
83 void xbt_os_thread_mod_preinit(void)
87 if (thread_mod_inited)
90 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
91 THROWF(system_error, errcode,
92 "pthread_key_create failed for xbt_self_thread_key");
94 main_thread = xbt_new(s_xbt_os_thread_t, 1);
95 main_thread->name = (char *) "main";
96 main_thread->start_routine = NULL;
97 main_thread->param = NULL;
98 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
99 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
101 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
102 THROWF(system_error, errcode,
103 "pthread_setspecific failed for xbt_self_thread_key");
106 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
107 __xbt_ex_terminate = _os_thread_ex_terminate;
109 thread_mod_inited = 1;
111 #ifndef HAVE_SEM_INIT
112 next_sem_ID_lock = xbt_os_mutex_init();
117 void xbt_os_thread_mod_postexit(void)
119 /* FIXME: don't try to free our key on shutdown.
120 Valgrind detects no leak if we don't, and whine if we try to */
123 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
124 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
125 free(main_thread->running_ctx);
128 thread_mod_inited = 0;
129 #ifndef HAVE_SEM_INIT
130 xbt_os_mutex_destroy(next_sem_ID_lock);
133 /* Restore the default exception setup */
134 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
135 __xbt_ex_terminate = &__xbt_ex_terminate_default;
138 int xbt_os_thread_atfork(void (*prepare)(void),
139 void (*parent)(void), void (*child)(void))
141 return pthread_atfork(prepare, parent, child);
144 static void *wrapper_start_routine(void *s)
146 xbt_os_thread_t t = s;
149 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
150 THROWF(system_error, errcode,
151 "pthread_setspecific failed for xbt_self_thread_key");
153 void *res = (*(t->start_routine)) (t->param);
155 xbt_os_thread_free_thread_data(t);
159 xbt_os_thread_t xbt_os_thread_create(const char *name,
160 pvoid_f_pvoid_t start_routine,
166 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
167 res_thread->detached = 0;
168 res_thread->name = xbt_strdup(name);
169 res_thread->start_routine = start_routine;
170 res_thread->param = param;
171 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
172 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
173 res_thread->extra_data = extra_data;
175 if ((errcode = pthread_create(&(res_thread->t), NULL,
176 wrapper_start_routine, res_thread)))
177 THROWF(system_error, errcode,
178 "pthread_create failed: %s", strerror(errcode));
183 const char *xbt_os_thread_name(xbt_os_thread_t t)
188 const char *xbt_os_thread_self_name(void)
190 xbt_os_thread_t me = xbt_os_thread_self();
191 return me ? me->name : "main";
194 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
199 if ((errcode = pthread_join(thread->t, thread_return)))
200 THROWF(system_error, errcode, "pthread_join failed: %s",
202 xbt_os_thread_free_thread_data(thread);
205 void xbt_os_thread_exit(int *retval)
207 pthread_exit(retval);
210 xbt_os_thread_t xbt_os_thread_self(void)
214 if (!thread_mod_inited)
217 res = pthread_getspecific(xbt_self_thread_key);
222 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
225 if ((errcode = pthread_key_create(key, NULL)))
226 THROWF(system_error, errcode, "pthread_key_create failed");
229 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
232 if ((errcode = pthread_setspecific(key, value)))
233 THROWF(system_error, errcode, "pthread_setspecific failed");
236 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
237 return pthread_getspecific(key);
240 void xbt_os_thread_detach(xbt_os_thread_t thread)
242 thread->detached = 1;
243 pthread_detach(thread->t);
247 void xbt_os_thread_yield(void)
252 void xbt_os_thread_cancel(xbt_os_thread_t t)
254 pthread_cancel(t->t);
257 /****** mutex related functions ******/
258 typedef struct xbt_os_mutex_ {
259 /* KEEP IT IN SYNC WITH xbt_thread.c */
266 xbt_os_mutex_t xbt_os_mutex_init(void)
268 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
271 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
272 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
278 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
282 if ((errcode = pthread_mutex_lock(&(mutex->m))))
283 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
284 mutex, strerror(errcode));
288 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
293 xbt_os_mutex_acquire(mutex);
295 } else if (delay == 0) {
296 errcode = pthread_mutex_trylock(&(mutex->m));
302 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
304 THROWF(system_error, errcode,
305 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
312 #ifdef HAVE_MUTEX_TIMEDLOCK
313 struct timespec ts_end;
314 double end = delay + xbt_os_time();
316 ts_end.tv_sec = (time_t) floor(end);
317 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
318 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
320 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
322 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
323 double start = xbt_os_time();
325 errcode = pthread_mutex_trylock(&(mutex->m));
326 if (errcode == EBUSY)
327 xbt_os_thread_yield();
328 } while (errcode == EBUSY && xbt_os_time() - start < delay);
330 if (errcode == EBUSY)
333 #endif /* HAVE_MUTEX_TIMEDLOCK */
340 THROWF(timeout_error, delay,
341 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
344 THROWF(system_error, errcode,
345 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
351 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
355 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
356 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
357 mutex, strerror(errcode));
360 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
367 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
368 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
369 mutex, strerror(errcode));
373 /***** condition related functions *****/
374 typedef struct xbt_os_cond_ {
375 /* KEEP IT IN SYNC WITH xbt_thread.c */
379 xbt_os_cond_t xbt_os_cond_init(void)
381 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
383 if ((errcode = pthread_cond_init(&(res->c), NULL)))
384 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
390 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
393 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
394 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
395 cond, mutex, strerror(errcode));
399 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
403 struct timespec ts_end;
404 double end = delay + xbt_os_time();
407 xbt_os_cond_wait(cond, mutex);
409 ts_end.tv_sec = (time_t) floor(end);
410 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
411 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
414 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
418 THROWF(timeout_error, errcode,
419 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
422 THROWF(system_error, errcode,
423 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
424 delay, strerror(errcode));
429 void xbt_os_cond_signal(xbt_os_cond_t cond)
432 if ((errcode = pthread_cond_signal(&(cond->c))))
433 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
434 cond, strerror(errcode));
437 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
440 if ((errcode = pthread_cond_broadcast(&(cond->c))))
441 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
442 cond, strerror(errcode));
445 void xbt_os_cond_destroy(xbt_os_cond_t cond)
452 if ((errcode = pthread_cond_destroy(&(cond->c))))
453 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
454 cond, strerror(errcode));
458 void *xbt_os_thread_getparam(void)
460 xbt_os_thread_t t = xbt_os_thread_self();
461 return t ? t->param : NULL;
464 typedef struct xbt_os_sem_ {
465 #ifndef HAVE_SEM_INIT
473 #define SEM_FAILED (-1)
476 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
478 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
480 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
481 * Any attempt to use it leads to ENOSYS (function not implemented).
482 * If such a prehistoric system is detected, do the job with sem_open instead
485 if (sem_init(&(res->s), 0, value) != 0)
486 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
489 #else /* damn, no sem_init(). Reimplement it */
491 xbt_os_mutex_acquire(next_sem_ID_lock);
492 res->name = bprintf("/%d", ++next_sem_ID);
493 xbt_os_mutex_release(next_sem_ID_lock);
495 res->ps = sem_open(res->name, O_CREAT, 0644, value);
496 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
497 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
498 res->name[13] = '\0';
499 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
501 if ((res->ps == (sem_t *) SEM_FAILED))
502 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
504 /* Remove the name from the semaphore namespace: we never join on it */
505 if (sem_unlink(res->name) < 0)
506 THROWF(system_error, errno, "sem_unlink() failed: %s",
514 void xbt_os_sem_acquire(xbt_os_sem_t sem)
517 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
518 if (sem_wait(sem->ps) < 0)
519 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
522 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
527 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
530 xbt_os_sem_acquire(sem);
531 } else if (delay == 0) {
532 errcode = sem_trywait(sem->ps);
538 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
540 THROWF(system_error, errcode,
541 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
547 struct timespec ts_end;
548 double end = delay + xbt_os_time();
550 ts_end.tv_sec = (time_t) floor(end);
551 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
552 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
553 errcode = sem_timedwait(sem->s, &ts_end);
555 #else /* Okay, reimplement this function then */
556 double start = xbt_os_time();
558 errcode = sem_trywait(sem->ps);
559 if (errcode == EBUSY)
560 xbt_os_thread_yield();
561 } while (errcode == EBUSY && xbt_os_time() - start < delay);
563 if (errcode == EBUSY)
572 THROWF(timeout_error, delay,
573 "semaphore %p wasn't signaled before timeout (%f)", sem,
577 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
578 delay, strerror(errcode));
583 void xbt_os_sem_release(xbt_os_sem_t sem)
586 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
588 if (sem_post(sem->ps) < 0)
589 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
592 void xbt_os_sem_destroy(xbt_os_sem_t sem)
595 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
598 if (sem_destroy(sem->ps) < 0)
599 THROWF(system_error, errno, "sem_destroy() failed: %s",
602 if (sem_close(sem->ps) < 0)
603 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
610 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
613 THROWF(arg_error, EINVAL,
614 "Cannot get the value of the NULL semaphore");
616 if (sem_getvalue(&(sem->s), svalue) < 0)
617 THROWF(system_error, errno, "sem_getvalue() failed: %s",
621 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
623 #elif defined(_XBT_WIN32)
627 typedef struct xbt_os_thread_ {
629 HANDLE handle; /* the win thread handle */
630 unsigned long id; /* the win thread id */
631 pvoid_f_pvoid_t start_routine;
636 /* so we can specify the size of the stack of the threads */
637 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
638 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
641 /* the default size of the stack of the threads (in bytes)*/
642 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
644 /* key to the TLS containing the xbt_os_thread_t structure */
645 static unsigned long xbt_self_thread_key;
647 void xbt_os_thread_mod_preinit(void)
649 xbt_self_thread_key = TlsAlloc();
652 void xbt_os_thread_mod_postexit(void)
655 if (!TlsFree(xbt_self_thread_key))
656 THROWF(system_error, (int) GetLastError(),
657 "TlsFree() failed to cleanup the thread submodule");
660 int xbt_os_thread_atfork(void (*prepare)(void),
661 void (*parent)(void), void (*child)(void))
666 static DWORD WINAPI wrapper_start_routine(void *s)
668 xbt_os_thread_t t = (xbt_os_thread_t) s;
671 if (!TlsSetValue(xbt_self_thread_key, t))
672 THROWF(system_error, (int) GetLastError(),
673 "TlsSetValue of data describing the created thread failed");
675 rv = (DWORD *) ((t->start_routine) (t->param));
682 xbt_os_thread_t xbt_os_thread_create(const char *name,
683 pvoid_f_pvoid_t start_routine,
688 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
690 t->name = xbt_strdup(name);
691 t->start_routine = start_routine;
693 t->extra_data = extra_data;
694 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
695 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
696 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
700 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
706 const char *xbt_os_thread_name(xbt_os_thread_t t)
711 const char *xbt_os_thread_self_name(void)
713 xbt_os_thread_t t = xbt_os_thread_self();
714 return t ? t->name : "main";
717 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
720 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
721 THROWF(system_error, (int) GetLastError(),
722 "WaitForSingleObject failed");
726 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
727 THROWF(system_error, (int) GetLastError(),
728 "GetExitCodeThread failed");
731 CloseHandle(thread->handle);
739 void xbt_os_thread_exit(int *retval)
747 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
752 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
754 if (!TlsSetValue(key, value))
755 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
758 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
759 return TlsGetValue(key);
762 void xbt_os_thread_detach(xbt_os_thread_t thread)
768 xbt_os_thread_t xbt_os_thread_self(void)
770 return TlsGetValue(xbt_self_thread_key);
773 void *xbt_os_thread_getparam(void)
775 xbt_os_thread_t t = xbt_os_thread_self();
780 void xbt_os_thread_yield(void)
785 void xbt_os_thread_cancel(xbt_os_thread_t t)
787 if (!TerminateThread(t->handle, 0))
788 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
791 /****** mutex related functions ******/
792 typedef struct xbt_os_mutex_ {
793 /* KEEP IT IN SYNC WITH xbt_thread.c */
794 CRITICAL_SECTION lock;
797 xbt_os_mutex_t xbt_os_mutex_init(void)
799 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
801 /* initialize the critical section object */
802 InitializeCriticalSection(&(res->lock));
807 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
809 EnterCriticalSection(&mutex->lock);
812 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
817 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
820 LeaveCriticalSection(&mutex->lock);
824 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
830 DeleteCriticalSection(&mutex->lock);
834 /***** condition related functions *****/
835 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
841 typedef struct xbt_os_cond_ {
842 /* KEEP IT IN SYNC WITH xbt_thread.c */
843 HANDLE events[MAX_EVENTS];
845 unsigned int waiters_count; /* the number of waiters */
846 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
849 xbt_os_cond_t xbt_os_cond_init(void)
852 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
854 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
856 /* initialize the critical section object */
857 InitializeCriticalSection(&res->waiters_count_lock);
859 res->waiters_count = 0;
861 /* Create an auto-reset event */
862 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
864 if (!res->events[SIGNAL]) {
865 DeleteCriticalSection(&res->waiters_count_lock);
867 THROWF(system_error, 0, "CreateEvent failed for the signals");
870 /* Create a manual-reset event. */
871 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
873 if (!res->events[BROADCAST]) {
875 DeleteCriticalSection(&res->waiters_count_lock);
876 CloseHandle(res->events[SIGNAL]);
878 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
884 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
887 unsigned long wait_result;
890 /* lock the threads counter and increment it */
891 EnterCriticalSection(&cond->waiters_count_lock);
892 cond->waiters_count++;
893 LeaveCriticalSection(&cond->waiters_count_lock);
895 /* unlock the mutex associate with the condition */
896 LeaveCriticalSection(&mutex->lock);
898 /* wait for a signal (broadcast or no) */
899 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
901 if (wait_result == WAIT_FAILED)
902 THROWF(system_error, 0,
903 "WaitForMultipleObjects failed, so we cannot wait on the condition");
905 /* we have a signal lock the condition */
906 EnterCriticalSection(&cond->waiters_count_lock);
907 cond->waiters_count--;
909 /* it's the last waiter or it's a broadcast ? */
910 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
911 && (cond->waiters_count == 0));
913 LeaveCriticalSection(&cond->waiters_count_lock);
915 /* yes it's the last waiter or it's a broadcast
916 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
920 if (!ResetEvent(cond->events[BROADCAST]))
921 THROWF(system_error, 0, "ResetEvent failed");
923 /* relock the mutex associated with the condition in accordance with the posix thread specification */
924 EnterCriticalSection(&mutex->lock);
927 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
931 unsigned long wait_result = WAIT_TIMEOUT;
933 unsigned long end = (unsigned long) (delay * 1000);
937 xbt_os_cond_wait(cond, mutex);
939 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
940 &(mutex->lock), end);
942 /* lock the threads counter and increment it */
943 EnterCriticalSection(&cond->waiters_count_lock);
944 cond->waiters_count++;
945 LeaveCriticalSection(&cond->waiters_count_lock);
947 /* unlock the mutex associate with the condition */
948 LeaveCriticalSection(&mutex->lock);
949 /* wait for a signal (broadcast or no) */
951 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
953 switch (wait_result) {
955 THROWF(timeout_error, GetLastError(),
956 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
959 THROWF(system_error, GetLastError(),
960 "WaitForMultipleObjects failed, so we cannot wait on the condition");
963 /* we have a signal lock the condition */
964 EnterCriticalSection(&cond->waiters_count_lock);
965 cond->waiters_count--;
967 /* it's the last waiter or it's a broadcast ? */
968 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
969 && (cond->waiters_count == 0));
971 LeaveCriticalSection(&cond->waiters_count_lock);
973 /* yes it's the last waiter or it's a broadcast
974 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
978 if (!ResetEvent(cond->events[BROADCAST]))
979 THROWF(system_error, 0, "ResetEvent failed");
981 /* relock the mutex associated with the condition in accordance with the posix thread specification */
982 EnterCriticalSection(&mutex->lock);
984 /*THROW_UNIMPLEMENTED; */
987 void xbt_os_cond_signal(xbt_os_cond_t cond)
991 EnterCriticalSection(&cond->waiters_count_lock);
992 have_waiters = cond->waiters_count > 0;
993 LeaveCriticalSection(&cond->waiters_count_lock);
996 if (!SetEvent(cond->events[SIGNAL]))
997 THROWF(system_error, 0, "SetEvent failed");
999 xbt_os_thread_yield();
1002 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1006 EnterCriticalSection(&cond->waiters_count_lock);
1007 have_waiters = cond->waiters_count > 0;
1008 LeaveCriticalSection(&cond->waiters_count_lock);
1011 SetEvent(cond->events[BROADCAST]);
1014 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1021 if (!CloseHandle(cond->events[SIGNAL]))
1024 if (!CloseHandle(cond->events[BROADCAST]))
1027 DeleteCriticalSection(&cond->waiters_count_lock);
1032 THROWF(system_error, 0, "Error while destroying the condition");
1035 typedef struct xbt_os_sem_ {
1038 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1042 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1045 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1049 if (value > INT_MAX)
1050 THROWF(arg_error, value,
1051 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1054 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1056 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1057 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1058 strerror(GetLastError()));
1064 InitializeCriticalSection(&(res->value_lock));
1069 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1072 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1075 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1076 THROWF(system_error, GetLastError(),
1077 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1078 EnterCriticalSection(&(sem->value_lock));
1080 LeaveCriticalSection(&(sem->value_lock));
1083 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1087 double end = timeout + xbt_os_time();
1090 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1093 xbt_os_sem_acquire(sem);
1094 } else { /* timeout can be zero <-> try acquire ) */
1097 seconds = (long) floor(end);
1098 milliseconds = (long) ((end - seconds) * 1000);
1099 milliseconds += (seconds * 1000);
1101 switch (WaitForSingleObject(sem->h, milliseconds)) {
1103 EnterCriticalSection(&(sem->value_lock));
1105 LeaveCriticalSection(&(sem->value_lock));
1109 THROWF(timeout_error, GetLastError(),
1110 "semaphore %p wasn't signaled before timeout (%f)", sem,
1115 THROWF(system_error, GetLastError(),
1116 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1117 strerror(GetLastError()));
1122 void xbt_os_sem_release(xbt_os_sem_t sem)
1125 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1127 if (!ReleaseSemaphore(sem->h, 1, NULL))
1128 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1129 strerror(GetLastError()));
1130 EnterCriticalSection(&(sem->value_lock));
1132 LeaveCriticalSection(&(sem->value_lock));
1135 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1138 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1140 if (!CloseHandle(sem->h))
1141 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1142 strerror(GetLastError()));
1144 DeleteCriticalSection(&(sem->value_lock));
1150 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1153 THROWF(arg_error, EINVAL,
1154 "Cannot get the value of the NULL semaphore");
1156 EnterCriticalSection(&(sem->value_lock));
1157 *svalue = sem->value;
1158 LeaveCriticalSection(&(sem->value_lock));
1164 /***** reentrant mutexes *****/
1165 typedef struct xbt_os_rmutex_ {
1166 xbt_os_mutex_t mutex;
1167 xbt_os_thread_t owner;
1169 } s_xbt_os_rmutex_t;
1171 void xbt_os_thread_set_extra_data(void *data)
1173 xbt_os_thread_self()->extra_data = data;
1176 void *xbt_os_thread_get_extra_data(void)
1178 return xbt_os_thread_self()->extra_data;
1181 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1183 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 0);
1184 rmutex->mutex = xbt_os_mutex_init();
1185 rmutex->owner = NULL;
1190 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1192 xbt_os_thread_t self = xbt_os_thread_self();
1195 /* the thread module is not initialized yet */
1196 rmutex->owner = NULL;
1200 if (self != rmutex->owner) {
1201 xbt_os_mutex_acquire(rmutex->mutex);
1202 rmutex->owner = self;
1209 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1211 if (rmutex->owner == NULL) {
1212 /* the thread module was not initialized */
1216 xbt_assert(rmutex->owner == xbt_os_thread_self());
1218 if (--rmutex->count == 0) {
1219 rmutex->owner = NULL;
1220 xbt_os_mutex_release(rmutex->mutex);
1224 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1226 xbt_os_mutex_destroy(rmutex->mutex);