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_ {
46 pvoid_f_pvoid_t start_routine;
47 xbt_running_ctx_t *running_ctx;
50 static xbt_os_thread_t main_thread = NULL;
52 /* thread-specific data containing the xbt_os_thread_t structure */
53 static pthread_key_t xbt_self_thread_key;
54 static int thread_mod_inited = 0;
56 /* frees the xbt_os_thread_t corresponding to the current thread */
57 static void xbt_os_thread_free_thread_data(void *d)
62 /* callback: context fetching */
63 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
65 return xbt_os_thread_self()->running_ctx;
68 /* callback: termination */
69 static void _os_thread_ex_terminate(xbt_ex_t * e)
74 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
77 void xbt_os_thread_mod_preinit(void)
81 if (thread_mod_inited)
84 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
85 THROW0(system_error, errcode,
86 "pthread_key_create failed for xbt_self_thread_key");
88 main_thread = xbt_new(s_xbt_os_thread_t, 1);
89 main_thread->name = (char *) "main";
90 main_thread->start_routine = NULL;
91 main_thread->param = NULL;
92 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
93 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
95 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
96 THROW0(system_error, errcode,
97 "pthread_setspecific failed for xbt_self_thread_key");
100 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
101 __xbt_ex_terminate = _os_thread_ex_terminate;
103 thread_mod_inited = 1;
105 #ifndef HAVE_SEM_INIT
106 next_sem_ID_lock = xbt_os_mutex_init();
111 void xbt_os_thread_mod_postexit(void)
113 /* FIXME: don't try to free our key on shutdown.
114 Valgrind detects no leak if we don't, and whine if we try to */
117 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
118 // THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
119 free(main_thread->running_ctx);
122 thread_mod_inited = 0;
123 #ifndef HAVE_SEM_INIT
124 xbt_os_mutex_destroy(next_sem_ID_lock);
127 /* Restore the default exception setup */
128 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
129 __xbt_ex_terminate = &__xbt_ex_terminate_default;
132 int xbt_os_thread_atfork(void (*prepare)(void),
133 void (*parent)(void), void (*child)(void))
135 return pthread_atfork(prepare, parent, child);
138 static void *wrapper_start_routine(void *s)
140 xbt_os_thread_t t = s;
143 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
144 THROW0(system_error, errcode,
145 "pthread_setspecific failed for xbt_self_thread_key");
147 return (*(t->start_routine)) (t->param);
150 xbt_os_thread_t xbt_os_thread_create(const char *name,
151 pvoid_f_pvoid_t start_routine,
157 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
158 res_thread->name = xbt_strdup(name);
159 res_thread->start_routine = start_routine;
160 res_thread->param = param;
161 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
162 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
163 res_thread->extra_data = extra_data;
165 if ((errcode = pthread_create(&(res_thread->t), NULL,
166 wrapper_start_routine, res_thread)))
167 THROW1(system_error, errcode,
168 "pthread_create failed: %s", strerror(errcode));
173 const char *xbt_os_thread_name(xbt_os_thread_t t)
178 const char *xbt_os_thread_self_name(void)
180 xbt_os_thread_t me = xbt_os_thread_self();
181 return me ? me->name : "main";
184 void xbt_os_thread_set_extra_data(void *data)
186 xbt_os_thread_self()->extra_data = data;
189 void *xbt_os_thread_get_extra_data(void)
191 return xbt_os_thread_self()->extra_data;
194 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
199 if ((errcode = pthread_join(thread->t, thread_return)))
200 THROW1(system_error, errcode, "pthread_join failed: %s",
202 if (thread->running_ctx)
203 free(thread->running_ctx);
208 if (thread == main_thread) /* just killed main thread */
214 void xbt_os_thread_exit(int *retval)
216 pthread_exit(retval);
219 xbt_os_thread_t xbt_os_thread_self(void)
223 if (!thread_mod_inited)
226 res = pthread_getspecific(xbt_self_thread_key);
231 void xbt_os_thread_detach(xbt_os_thread_t thread)
233 pthread_detach(thread->t);
237 void xbt_os_thread_yield(void)
242 void xbt_os_thread_cancel(xbt_os_thread_t t)
244 pthread_cancel(t->t);
247 /****** mutex related functions ******/
248 typedef struct xbt_os_mutex_ {
249 /* KEEP IT IN SYNC WITH xbt_thread.c */
256 xbt_os_mutex_t xbt_os_mutex_init(void)
258 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
261 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
262 THROW1(system_error, errcode, "pthread_mutex_init() failed: %s",
268 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
272 if ((errcode = pthread_mutex_lock(&(mutex->m))))
273 THROW2(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
274 mutex, strerror(errcode));
278 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
283 xbt_os_mutex_acquire(mutex);
285 } else if (delay == 0) {
286 errcode = pthread_mutex_trylock(&(mutex->m));
292 THROW1(timeout_error, 0, "mutex %p not ready", mutex);
294 THROW2(system_error, errcode,
295 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
302 #ifdef HAVE_MUTEX_TIMEDLOCK
303 struct timespec ts_end;
304 double end = delay + xbt_os_time();
306 ts_end.tv_sec = (time_t) floor(end);
307 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
308 DEBUG2("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
310 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
312 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
313 double start = xbt_os_time();
315 errcode = pthread_mutex_trylock(&(mutex->m));
316 if (errcode == EBUSY)
317 xbt_os_thread_yield();
318 } while (errcode == EBUSY && xbt_os_time() - start < delay);
320 if (errcode == EBUSY)
323 #endif /* HAVE_MUTEX_TIMEDLOCK */
330 THROW2(timeout_error, delay,
331 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
334 THROW3(system_error, errcode,
335 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
341 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
345 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
346 THROW2(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
347 mutex, strerror(errcode));
350 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
357 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
358 THROW2(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
359 mutex, strerror(errcode));
363 /***** condition related functions *****/
364 typedef struct xbt_os_cond_ {
365 /* KEEP IT IN SYNC WITH xbt_thread.c */
369 xbt_os_cond_t xbt_os_cond_init(void)
371 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
373 if ((errcode = pthread_cond_init(&(res->c), NULL)))
374 THROW1(system_error, errcode, "pthread_cond_init() failed: %s",
380 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
383 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
384 THROW3(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
385 cond, mutex, strerror(errcode));
389 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
393 struct timespec ts_end;
394 double end = delay + xbt_os_time();
397 xbt_os_cond_wait(cond, mutex);
399 ts_end.tv_sec = (time_t) floor(end);
400 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
401 DEBUG3("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
404 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
408 THROW3(timeout_error, errcode,
409 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
412 THROW4(system_error, errcode,
413 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
414 delay, strerror(errcode));
419 void xbt_os_cond_signal(xbt_os_cond_t cond)
422 if ((errcode = pthread_cond_signal(&(cond->c))))
423 THROW2(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
424 cond, strerror(errcode));
427 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
430 if ((errcode = pthread_cond_broadcast(&(cond->c))))
431 THROW2(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
432 cond, strerror(errcode));
435 void xbt_os_cond_destroy(xbt_os_cond_t cond)
442 if ((errcode = pthread_cond_destroy(&(cond->c))))
443 THROW2(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
444 cond, strerror(errcode));
448 void *xbt_os_thread_getparam(void)
450 xbt_os_thread_t t = xbt_os_thread_self();
451 return t ? t->param : NULL;
454 typedef struct xbt_os_sem_ {
455 #ifndef HAVE_SEM_INIT
463 #define SEM_FAILED (-1)
466 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
468 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
470 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
471 * Any attempt to use it leads to ENOSYS (function not implemented).
472 * If such a prehistoric system is detected, do the job with sem_open instead
475 if (sem_init(&(res->s), 0, value) != 0)
476 THROW1(system_error, errno, "sem_init() failed: %s", strerror(errno));
479 #else /* damn, no sem_init(). Reimplement it */
481 xbt_os_mutex_acquire(next_sem_ID_lock);
482 res->name = bprintf("/%d", ++next_sem_ID);
483 xbt_os_mutex_release(next_sem_ID_lock);
485 res->ps = sem_open(res->name, O_CREAT, 0644, value);
486 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
487 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
488 res->name[13] = '\0';
489 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
491 if ((res->ps == (sem_t *) SEM_FAILED))
492 THROW1(system_error, errno, "sem_open() failed: %s", strerror(errno));
494 /* Remove the name from the semaphore namespace: we never join on it */
495 if (sem_unlink(res->name) < 0)
496 THROW1(system_error, errno, "sem_unlink() failed: %s",
504 void xbt_os_sem_acquire(xbt_os_sem_t sem)
507 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
508 if (sem_wait(sem->ps) < 0)
509 THROW1(system_error, errno, "sem_wait() failed: %s", strerror(errno));
512 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
517 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
520 xbt_os_sem_acquire(sem);
521 } else if (delay == 0) {
522 errcode = sem_trywait(sem->ps);
528 THROW1(timeout_error, 0, "semaphore %p not ready", sem);
530 THROW2(system_error, errcode,
531 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
537 struct timespec ts_end;
538 double end = delay + xbt_os_time();
540 ts_end.tv_sec = (time_t) floor(end);
541 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
542 DEBUG2("sem_timedwait(%p,%p)", sem->ps, &ts_end);
543 errcode = sem_timedwait(sem->s, &ts_end);
545 #else /* Okay, reimplement this function then */
546 double start = xbt_os_time();
548 errcode = sem_trywait(sem->ps);
549 if (errcode == EBUSY)
550 xbt_os_thread_yield();
551 } while (errcode == EBUSY && xbt_os_time() - start < delay);
553 if (errcode == EBUSY)
562 THROW2(timeout_error, delay,
563 "semaphore %p wasn't signaled before timeout (%f)", sem,
567 THROW3(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
568 delay, strerror(errcode));
573 void xbt_os_sem_release(xbt_os_sem_t sem)
576 THROW0(arg_error, EINVAL, "Cannot release of the NULL semaphore");
578 if (sem_post(sem->ps) < 0)
579 THROW1(system_error, errno, "sem_post() failed: %s", strerror(errno));
582 void xbt_os_sem_destroy(xbt_os_sem_t sem)
585 THROW0(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
588 if (sem_destroy(sem->ps) < 0)
589 THROW1(system_error, errno, "sem_destroy() failed: %s",
592 if (sem_close(sem->ps) < 0)
593 THROW1(system_error, errno, "sem_close() failed: %s", strerror(errno));
600 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
603 THROW0(arg_error, EINVAL,
604 "Cannot get the value of the NULL semaphore");
606 if (sem_getvalue(&(sem->s), svalue) < 0)
607 THROW1(system_error, errno, "sem_getvalue() failed: %s",
611 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
613 #elif defined(_XBT_WIN32)
617 typedef struct xbt_os_thread_ {
619 HANDLE handle; /* the win thread handle */
620 unsigned long id; /* the win thread id */
621 pvoid_f_pvoid_t start_routine;
626 /* so we can specify the size of the stack of the threads */
627 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
628 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
631 /* the default size of the stack of the threads (in bytes)*/
632 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
634 /* key to the TLS containing the xbt_os_thread_t structure */
635 static unsigned long xbt_self_thread_key;
637 void xbt_os_thread_mod_preinit(void)
639 xbt_self_thread_key = TlsAlloc();
642 void xbt_os_thread_mod_postexit(void)
645 if (!TlsFree(xbt_self_thread_key))
646 THROW0(system_error, (int) GetLastError(),
647 "TlsFree() failed to cleanup the thread submodule");
650 int xbt_os_thread_atfork(void (*prepare)(void),
651 void (*parent)(void), void (*child)(void))
656 static DWORD WINAPI wrapper_start_routine(void *s)
658 xbt_os_thread_t t = (xbt_os_thread_t) s;
661 if (!TlsSetValue(xbt_self_thread_key, t))
662 THROW0(system_error, (int) GetLastError(),
663 "TlsSetValue of data describing the created thread failed");
665 rv = (DWORD *) ((t->start_routine) (t->param));
672 xbt_os_thread_t xbt_os_thread_create(const char *name,
673 pvoid_f_pvoid_t start_routine,
678 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
680 t->name = xbt_strdup(name);
681 t->start_routine = start_routine;
683 t->extra_data = extra_data;
684 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
685 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
686 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
690 THROW0(system_error, (int) GetLastError(), "CreateThread failed");
696 const char *xbt_os_thread_name(xbt_os_thread_t t)
701 const char *xbt_os_thread_self_name(void)
703 xbt_os_thread_t t = xbt_os_thread_self();
704 return t ? t->name : "main";
707 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
710 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
711 THROW0(system_error, (int) GetLastError(),
712 "WaitForSingleObject failed");
716 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
717 THROW0(system_error, (int) GetLastError(),
718 "GetExitCodeThread failed");
721 CloseHandle(thread->handle);
729 void xbt_os_thread_exit(int *retval)
737 void xbt_os_thread_detach(xbt_os_thread_t thread)
743 xbt_os_thread_t xbt_os_thread_self(void)
745 return TlsGetValue(xbt_self_thread_key);
748 void *xbt_os_thread_getparam(void)
750 xbt_os_thread_t t = xbt_os_thread_self();
755 void xbt_os_thread_yield(void)
760 void xbt_os_thread_cancel(xbt_os_thread_t t)
762 if (!TerminateThread(t->handle, 0))
763 THROW0(system_error, (int) GetLastError(), "TerminateThread failed");
766 /****** mutex related functions ******/
767 typedef struct xbt_os_mutex_ {
768 /* KEEP IT IN SYNC WITH xbt_thread.c */
769 CRITICAL_SECTION lock;
772 xbt_os_mutex_t xbt_os_mutex_init(void)
774 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
776 /* initialize the critical section object */
777 InitializeCriticalSection(&(res->lock));
782 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
784 EnterCriticalSection(&mutex->lock);
787 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
792 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
795 LeaveCriticalSection(&mutex->lock);
799 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
805 DeleteCriticalSection(&mutex->lock);
809 /***** condition related functions *****/
810 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
816 typedef struct xbt_os_cond_ {
817 /* KEEP IT IN SYNC WITH xbt_thread.c */
818 HANDLE events[MAX_EVENTS];
820 unsigned int waiters_count; /* the number of waiters */
821 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
824 xbt_os_cond_t xbt_os_cond_init(void)
827 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
829 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
831 /* initialize the critical section object */
832 InitializeCriticalSection(&res->waiters_count_lock);
834 res->waiters_count = 0;
836 /* Create an auto-reset event */
837 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
839 if (!res->events[SIGNAL]) {
840 DeleteCriticalSection(&res->waiters_count_lock);
842 THROW0(system_error, 0, "CreateEvent failed for the signals");
845 /* Create a manual-reset event. */
846 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
848 if (!res->events[BROADCAST]) {
850 DeleteCriticalSection(&res->waiters_count_lock);
851 CloseHandle(res->events[SIGNAL]);
853 THROW0(system_error, 0, "CreateEvent failed for the broadcasts");
859 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
862 unsigned long wait_result;
865 /* lock the threads counter and increment it */
866 EnterCriticalSection(&cond->waiters_count_lock);
867 cond->waiters_count++;
868 LeaveCriticalSection(&cond->waiters_count_lock);
870 /* unlock the mutex associate with the condition */
871 LeaveCriticalSection(&mutex->lock);
873 /* wait for a signal (broadcast or no) */
874 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
876 if (wait_result == WAIT_FAILED)
877 THROW0(system_error, 0,
878 "WaitForMultipleObjects failed, so we cannot wait on the condition");
880 /* we have a signal lock the condition */
881 EnterCriticalSection(&cond->waiters_count_lock);
882 cond->waiters_count--;
884 /* it's the last waiter or it's a broadcast ? */
885 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
886 && (cond->waiters_count == 0));
888 LeaveCriticalSection(&cond->waiters_count_lock);
890 /* yes it's the last waiter or it's a broadcast
891 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
895 if (!ResetEvent(cond->events[BROADCAST]))
896 THROW0(system_error, 0, "ResetEvent failed");
898 /* relock the mutex associated with the condition in accordance with the posix thread specification */
899 EnterCriticalSection(&mutex->lock);
902 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
906 unsigned long wait_result = WAIT_TIMEOUT;
908 unsigned long end = (unsigned long) (delay * 1000);
912 xbt_os_cond_wait(cond, mutex);
914 DEBUG3("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
915 &(mutex->lock), end);
917 /* lock the threads counter and increment it */
918 EnterCriticalSection(&cond->waiters_count_lock);
919 cond->waiters_count++;
920 LeaveCriticalSection(&cond->waiters_count_lock);
922 /* unlock the mutex associate with the condition */
923 LeaveCriticalSection(&mutex->lock);
924 /* wait for a signal (broadcast or no) */
926 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
928 switch (wait_result) {
930 THROW3(timeout_error, GetLastError(),
931 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
934 THROW0(system_error, GetLastError(),
935 "WaitForMultipleObjects failed, so we cannot wait on the condition");
938 /* we have a signal lock the condition */
939 EnterCriticalSection(&cond->waiters_count_lock);
940 cond->waiters_count--;
942 /* it's the last waiter or it's a broadcast ? */
943 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
944 && (cond->waiters_count == 0));
946 LeaveCriticalSection(&cond->waiters_count_lock);
948 /* yes it's the last waiter or it's a broadcast
949 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
953 if (!ResetEvent(cond->events[BROADCAST]))
954 THROW0(system_error, 0, "ResetEvent failed");
956 /* relock the mutex associated with the condition in accordance with the posix thread specification */
957 EnterCriticalSection(&mutex->lock);
959 /*THROW_UNIMPLEMENTED; */
962 void xbt_os_cond_signal(xbt_os_cond_t cond)
966 EnterCriticalSection(&cond->waiters_count_lock);
967 have_waiters = cond->waiters_count > 0;
968 LeaveCriticalSection(&cond->waiters_count_lock);
971 if (!SetEvent(cond->events[SIGNAL]))
972 THROW0(system_error, 0, "SetEvent failed");
974 xbt_os_thread_yield();
977 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
981 EnterCriticalSection(&cond->waiters_count_lock);
982 have_waiters = cond->waiters_count > 0;
983 LeaveCriticalSection(&cond->waiters_count_lock);
986 SetEvent(cond->events[BROADCAST]);
989 void xbt_os_cond_destroy(xbt_os_cond_t cond)
996 if (!CloseHandle(cond->events[SIGNAL]))
999 if (!CloseHandle(cond->events[BROADCAST]))
1002 DeleteCriticalSection(&cond->waiters_count_lock);
1007 THROW0(system_error, 0, "Error while destroying the condition");
1010 typedef struct xbt_os_sem_ {
1013 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1017 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1020 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1024 if (value > INT_MAX)
1025 THROW1(arg_error, value,
1026 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1029 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1031 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1032 THROW1(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1033 strerror(GetLastError()));
1039 InitializeCriticalSection(&(res->value_lock));
1044 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1047 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1050 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1051 THROW1(system_error, GetLastError(),
1052 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1053 EnterCriticalSection(&(sem->value_lock));
1055 LeaveCriticalSection(&(sem->value_lock));
1058 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1062 double end = timeout + xbt_os_time();
1065 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1068 xbt_os_sem_acquire(sem);
1069 } else { /* timeout can be zero <-> try acquire ) */
1072 seconds = (long) floor(end);
1073 milliseconds = (long) ((end - seconds) * 1000);
1074 milliseconds += (seconds * 1000);
1076 switch (WaitForSingleObject(sem->h, milliseconds)) {
1078 EnterCriticalSection(&(sem->value_lock));
1080 LeaveCriticalSection(&(sem->value_lock));
1084 THROW2(timeout_error, GetLastError(),
1085 "semaphore %p wasn't signaled before timeout (%f)", sem,
1090 THROW3(system_error, GetLastError(),
1091 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1092 strerror(GetLastError()));
1097 void xbt_os_sem_release(xbt_os_sem_t sem)
1100 THROW0(arg_error, EINVAL, "Cannot release the NULL semaphore");
1102 if (!ReleaseSemaphore(sem->h, 1, NULL))
1103 THROW1(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1104 strerror(GetLastError()));
1105 EnterCriticalSection(&(sem->value_lock));
1107 LeaveCriticalSection(&(sem->value_lock));
1110 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1113 THROW0(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1115 if (!CloseHandle(sem->h))
1116 THROW1(system_error, GetLastError(), "CloseHandle() failed: %s",
1117 strerror(GetLastError()));
1119 DeleteCriticalSection(&(sem->value_lock));
1125 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1128 THROW0(arg_error, EINVAL,
1129 "Cannot get the value of the NULL semaphore");
1131 EnterCriticalSection(&(sem->value_lock));
1132 *svalue = sem->value;
1133 LeaveCriticalSection(&(sem->value_lock));