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 "xbt/sysdep.h"
13 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
15 #include "xbt/xbt_os_time.h" /* Portable time facilities */
16 #include "xbt/xbt_os_thread.h" /* This module */
17 #include "xbt_modinter.h" /* Initialization/finalization of this module */
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
20 "Synchronization mechanism (OS-level)");
22 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
26 #include <semaphore.h>
28 #ifdef HAVE_MUTEX_TIMEDLOCK
29 /* redefine the function header since we fail to get this from system headers on amd (at least) */
30 int pthread_mutex_timedlock(pthread_mutex_t * mutex,
31 const struct timespec *abs_timeout);
35 /* use named sempahore when sem_init() does not work */
37 static int next_sem_ID = 0;
38 static xbt_os_mutex_t next_sem_ID_lock;
41 typedef struct xbt_os_thread_ {
45 pvoid_f_pvoid_t start_routine;
46 xbt_running_ctx_t *running_ctx;
49 static xbt_os_thread_t main_thread = NULL;
51 /* thread-specific data containing the xbt_os_thread_t structure */
52 static pthread_key_t xbt_self_thread_key;
53 static int thread_mod_inited = 0;
55 /* frees the xbt_os_thread_t corresponding to the current thread */
56 static void xbt_os_thread_free_thread_data(void *d)
61 /* callback: context fetching */
62 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
64 return xbt_os_thread_self()->running_ctx;
67 /* callback: termination */
68 static void _os_thread_ex_terminate(xbt_ex_t * e)
73 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
76 void xbt_os_thread_mod_preinit(void)
80 if (thread_mod_inited)
83 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
84 THROW0(system_error, errcode,
85 "pthread_key_create failed for xbt_self_thread_key");
87 main_thread = xbt_new(s_xbt_os_thread_t, 1);
88 main_thread->name = (char *) "main";
89 main_thread->start_routine = NULL;
90 main_thread->param = NULL;
91 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
92 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
94 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
95 THROW0(system_error, errcode,
96 "pthread_setspecific failed for xbt_self_thread_key");
99 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
100 __xbt_ex_terminate = _os_thread_ex_terminate;
102 thread_mod_inited = 1;
104 #ifndef HAVE_SEM_INIT
105 next_sem_ID_lock = xbt_os_mutex_init();
110 void xbt_os_thread_mod_postexit(void)
112 /* FIXME: don't try to free our key on shutdown.
113 Valgrind detects no leak if we don't, and whine if we try to */
116 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
117 // THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
118 free(main_thread->running_ctx);
121 thread_mod_inited = 0;
122 #ifndef HAVE_SEM_INIT
123 xbt_os_mutex_destroy(next_sem_ID_lock);
126 /* Restore the default exception setup */
127 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
128 __xbt_ex_terminate = &__xbt_ex_terminate_default;
131 int xbt_os_thread_atfork(void (*prepare)(void),
132 void (*parent)(void), void (*child)(void))
134 return pthread_atfork(prepare, parent, child);
137 static void *wrapper_start_routine(void *s)
139 xbt_os_thread_t t = s;
142 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
143 THROW0(system_error, errcode,
144 "pthread_setspecific failed for xbt_self_thread_key");
146 return (*(t->start_routine)) (t->param);
149 xbt_os_thread_t xbt_os_thread_create(const char *name,
150 pvoid_f_pvoid_t start_routine,
156 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
157 res_thread->name = xbt_strdup(name);
158 res_thread->start_routine = start_routine;
159 res_thread->param = param;
160 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
161 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
162 res_thread->extra_data = extra_data;
164 if ((errcode = pthread_create(&(res_thread->t), NULL,
165 wrapper_start_routine, res_thread)))
166 THROW1(system_error, errcode,
167 "pthread_create failed: %s", strerror(errcode));
172 const char *xbt_os_thread_name(xbt_os_thread_t t)
177 const char *xbt_os_thread_self_name(void)
179 xbt_os_thread_t me = xbt_os_thread_self();
180 return me ? me->name : "main";
183 void xbt_os_thread_set_extra_data(void *data)
185 xbt_os_thread_self()->extra_data = data;
188 void *xbt_os_thread_get_extra_data(void)
190 return xbt_os_thread_self()->extra_data;
193 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
198 if ((errcode = pthread_join(thread->t, thread_return)))
199 THROW1(system_error, errcode, "pthread_join failed: %s",
201 if (thread->running_ctx)
202 free(thread->running_ctx);
207 if (thread == main_thread) /* just killed main thread */
213 void xbt_os_thread_exit(int *retval)
215 pthread_exit(retval);
218 xbt_os_thread_t xbt_os_thread_self(void)
222 if (!thread_mod_inited)
225 res = pthread_getspecific(xbt_self_thread_key);
230 void xbt_os_thread_detach(xbt_os_thread_t thread)
232 pthread_detach(thread->t);
236 void xbt_os_thread_yield(void)
241 void xbt_os_thread_cancel(xbt_os_thread_t t)
243 pthread_cancel(t->t);
246 /****** mutex related functions ******/
247 typedef struct xbt_os_mutex_ {
248 /* KEEP IT IN SYNC WITH xbt_thread.c */
255 xbt_os_mutex_t xbt_os_mutex_init(void)
257 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
260 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
261 THROW1(system_error, errcode, "pthread_mutex_init() failed: %s",
267 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
271 if ((errcode = pthread_mutex_lock(&(mutex->m))))
272 THROW2(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
273 mutex, strerror(errcode));
277 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
282 xbt_os_mutex_acquire(mutex);
284 } else if (delay == 0) {
285 errcode = pthread_mutex_trylock(&(mutex->m));
291 THROW1(timeout_error, 0, "mutex %p not ready", mutex);
293 THROW2(system_error, errcode,
294 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
301 #ifdef HAVE_MUTEX_TIMEDLOCK
302 struct timespec ts_end;
303 double end = delay + xbt_os_time();
305 ts_end.tv_sec = (time_t) floor(end);
306 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
307 DEBUG2("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
309 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
311 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
312 double start = xbt_os_time();
314 errcode = pthread_mutex_trylock(&(mutex->m));
315 if (errcode == EBUSY)
316 xbt_os_thread_yield();
317 } while (errcode == EBUSY && xbt_os_time() - start < delay);
319 if (errcode == EBUSY)
322 #endif /* HAVE_MUTEX_TIMEDLOCK */
329 THROW2(timeout_error, delay,
330 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
333 THROW3(system_error, errcode,
334 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
340 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
344 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
345 THROW2(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
346 mutex, strerror(errcode));
349 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
356 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
357 THROW2(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
358 mutex, strerror(errcode));
362 /***** condition related functions *****/
363 typedef struct xbt_os_cond_ {
364 /* KEEP IT IN SYNC WITH xbt_thread.c */
368 xbt_os_cond_t xbt_os_cond_init(void)
370 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
372 if ((errcode = pthread_cond_init(&(res->c), NULL)))
373 THROW1(system_error, errcode, "pthread_cond_init() failed: %s",
379 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
382 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
383 THROW3(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
384 cond, mutex, strerror(errcode));
388 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
392 struct timespec ts_end;
393 double end = delay + xbt_os_time();
396 xbt_os_cond_wait(cond, mutex);
398 ts_end.tv_sec = (time_t) floor(end);
399 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
400 DEBUG3("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
403 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
407 THROW3(timeout_error, errcode,
408 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
411 THROW4(system_error, errcode,
412 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
413 delay, strerror(errcode));
418 void xbt_os_cond_signal(xbt_os_cond_t cond)
421 if ((errcode = pthread_cond_signal(&(cond->c))))
422 THROW2(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
423 cond, strerror(errcode));
426 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
429 if ((errcode = pthread_cond_broadcast(&(cond->c))))
430 THROW2(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
431 cond, strerror(errcode));
434 void xbt_os_cond_destroy(xbt_os_cond_t cond)
441 if ((errcode = pthread_cond_destroy(&(cond->c))))
442 THROW2(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
443 cond, strerror(errcode));
447 void *xbt_os_thread_getparam(void)
449 xbt_os_thread_t t = xbt_os_thread_self();
450 return t ? t->param : NULL;
453 typedef struct xbt_os_sem_ {
454 #ifndef HAVE_SEM_INIT
462 #define SEM_FAILED (-1)
465 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
467 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
469 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
470 * Any attempt to use it leads to ENOSYS (function not implemented).
471 * If such a prehistoric system is detected, do the job with sem_open instead
474 if (sem_init(&(res->s), 0, value) != 0)
475 THROW1(system_error, errno, "sem_init() failed: %s", strerror(errno));
478 #else /* damn, no sem_init(). Reimplement it */
480 xbt_os_mutex_acquire(next_sem_ID_lock);
481 res->name = bprintf("/%d", ++next_sem_ID);
482 xbt_os_mutex_release(next_sem_ID_lock);
484 res->ps = sem_open(res->name, O_CREAT, 0644, value);
485 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
486 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
487 res->name[13] = '\0';
488 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
490 if ((res->ps == (sem_t *) SEM_FAILED))
491 THROW1(system_error, errno, "sem_open() failed: %s", strerror(errno));
493 /* Remove the name from the semaphore namespace: we never join on it */
494 if (sem_unlink(res->name) < 0)
495 THROW1(system_error, errno, "sem_unlink() failed: %s",
503 void xbt_os_sem_acquire(xbt_os_sem_t sem)
506 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
507 if (sem_wait(sem->ps) < 0)
508 THROW1(system_error, errno, "sem_wait() failed: %s", strerror(errno));
511 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
516 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
519 xbt_os_sem_acquire(sem);
520 } else if (delay == 0) {
521 errcode = sem_trywait(sem->ps);
527 THROW1(timeout_error, 0, "semaphore %p not ready", sem);
529 THROW2(system_error, errcode,
530 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
536 struct timespec ts_end;
537 double end = delay + xbt_os_time();
539 ts_end.tv_sec = (time_t) floor(end);
540 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
541 DEBUG2("sem_timedwait(%p,%p)", sem->ps, &ts_end);
542 errcode = sem_timedwait(sem->s, &ts_end);
544 #else /* Okay, reimplement this function then */
545 double start = xbt_os_time();
547 errcode = sem_trywait(sem->ps);
548 if (errcode == EBUSY)
549 xbt_os_thread_yield();
550 } while (errcode == EBUSY && xbt_os_time() - start < delay);
552 if (errcode == EBUSY)
561 THROW2(timeout_error, delay,
562 "semaphore %p wasn't signaled before timeout (%f)", sem,
566 THROW3(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
567 delay, strerror(errcode));
572 void xbt_os_sem_release(xbt_os_sem_t sem)
575 THROW0(arg_error, EINVAL, "Cannot release of the NULL semaphore");
577 if (sem_post(sem->ps) < 0)
578 THROW1(system_error, errno, "sem_post() failed: %s", strerror(errno));
581 void xbt_os_sem_destroy(xbt_os_sem_t sem)
584 THROW0(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
587 if (sem_destroy(sem->ps) < 0)
588 THROW1(system_error, errno, "sem_destroy() failed: %s",
591 if (sem_close(sem->ps) < 0)
592 THROW1(system_error, errno, "sem_close() failed: %s", strerror(errno));
599 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
602 THROW0(arg_error, EINVAL,
603 "Cannot get the value of the NULL semaphore");
605 if (sem_getvalue(&(sem->s), svalue) < 0)
606 THROW1(system_error, errno, "sem_getvalue() failed: %s",
610 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
612 #elif defined(_XBT_WIN32)
616 typedef struct xbt_os_thread_ {
618 HANDLE handle; /* the win thread handle */
619 unsigned long id; /* the win thread id */
620 pvoid_f_pvoid_t start_routine;
624 /* so we can specify the size of the stack of the threads */
625 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
626 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
629 /* the default size of the stack of the threads (in bytes)*/
630 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
632 /* key to the TLS containing the xbt_os_thread_t structure */
633 static unsigned long xbt_self_thread_key;
635 void xbt_os_thread_mod_preinit(void)
637 xbt_self_thread_key = TlsAlloc();
640 void xbt_os_thread_mod_postexit(void)
643 if (!TlsFree(xbt_self_thread_key))
644 THROW0(system_error, (int) GetLastError(),
645 "TlsFree() failed to cleanup the thread submodule");
648 int xbt_os_thread_atfork(void (*prepare)(void),
649 void (*parent)(void), void (*child)(void))
654 static DWORD WINAPI wrapper_start_routine(void *s)
656 xbt_os_thread_t t = (xbt_os_thread_t) s;
659 if (!TlsSetValue(xbt_self_thread_key, t))
660 THROW0(system_error, (int) GetLastError(),
661 "TlsSetValue of data describing the created thread failed");
663 rv = (DWORD *) ((t->start_routine) (t->param));
670 xbt_os_thread_t xbt_os_thread_create(const char *name,
671 pvoid_f_pvoid_t start_routine,
675 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
677 t->name = xbt_strdup(name);
678 t->start_routine = start_routine;
681 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
682 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
683 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
687 THROW0(system_error, (int) GetLastError(), "CreateThread failed");
693 const char *xbt_os_thread_name(xbt_os_thread_t t)
698 const char *xbt_os_thread_self_name(void)
700 xbt_os_thread_t t = xbt_os_thread_self();
701 return t ? t->name : "main";
704 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
707 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
708 THROW0(system_error, (int) GetLastError(),
709 "WaitForSingleObject failed");
713 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
714 THROW0(system_error, (int) GetLastError(),
715 "GetExitCodeThread failed");
718 CloseHandle(thread->handle);
726 void xbt_os_thread_exit(int *retval)
734 void xbt_os_thread_detach(xbt_os_thread_t thread)
740 xbt_os_thread_t xbt_os_thread_self(void)
742 return TlsGetValue(xbt_self_thread_key);
745 void *xbt_os_thread_getparam(void)
747 xbt_os_thread_t t = xbt_os_thread_self();
752 void xbt_os_thread_yield(void)
757 void xbt_os_thread_cancel(xbt_os_thread_t t)
759 if (!TerminateThread(t->handle, 0))
760 THROW0(system_error, (int) GetLastError(), "TerminateThread failed");
763 /****** mutex related functions ******/
764 typedef struct xbt_os_mutex_ {
765 /* KEEP IT IN SYNC WITH xbt_thread.c */
766 CRITICAL_SECTION lock;
769 xbt_os_mutex_t xbt_os_mutex_init(void)
771 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
773 /* initialize the critical section object */
774 InitializeCriticalSection(&(res->lock));
779 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
781 EnterCriticalSection(&mutex->lock);
784 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
789 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
792 LeaveCriticalSection(&mutex->lock);
796 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
802 DeleteCriticalSection(&mutex->lock);
806 /***** condition related functions *****/
807 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
813 typedef struct xbt_os_cond_ {
814 /* KEEP IT IN SYNC WITH xbt_thread.c */
815 HANDLE events[MAX_EVENTS];
817 unsigned int waiters_count; /* the number of waiters */
818 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
821 xbt_os_cond_t xbt_os_cond_init(void)
824 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
826 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
828 /* initialize the critical section object */
829 InitializeCriticalSection(&res->waiters_count_lock);
831 res->waiters_count = 0;
833 /* Create an auto-reset event */
834 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
836 if (!res->events[SIGNAL]) {
837 DeleteCriticalSection(&res->waiters_count_lock);
839 THROW0(system_error, 0, "CreateEvent failed for the signals");
842 /* Create a manual-reset event. */
843 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
845 if (!res->events[BROADCAST]) {
847 DeleteCriticalSection(&res->waiters_count_lock);
848 CloseHandle(res->events[SIGNAL]);
850 THROW0(system_error, 0, "CreateEvent failed for the broadcasts");
856 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
859 unsigned long wait_result;
862 /* lock the threads counter and increment it */
863 EnterCriticalSection(&cond->waiters_count_lock);
864 cond->waiters_count++;
865 LeaveCriticalSection(&cond->waiters_count_lock);
867 /* unlock the mutex associate with the condition */
868 LeaveCriticalSection(&mutex->lock);
870 /* wait for a signal (broadcast or no) */
871 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
873 if (wait_result == WAIT_FAILED)
874 THROW0(system_error, 0,
875 "WaitForMultipleObjects failed, so we cannot wait on the condition");
877 /* we have a signal lock the condition */
878 EnterCriticalSection(&cond->waiters_count_lock);
879 cond->waiters_count--;
881 /* it's the last waiter or it's a broadcast ? */
882 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
883 && (cond->waiters_count == 0));
885 LeaveCriticalSection(&cond->waiters_count_lock);
887 /* yes it's the last waiter or it's a broadcast
888 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
892 if (!ResetEvent(cond->events[BROADCAST]))
893 THROW0(system_error, 0, "ResetEvent failed");
895 /* relock the mutex associated with the condition in accordance with the posix thread specification */
896 EnterCriticalSection(&mutex->lock);
899 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
903 unsigned long wait_result = WAIT_TIMEOUT;
905 unsigned long end = (unsigned long) (delay * 1000);
909 xbt_os_cond_wait(cond, mutex);
911 DEBUG3("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
912 &(mutex->lock), end);
914 /* lock the threads counter and increment it */
915 EnterCriticalSection(&cond->waiters_count_lock);
916 cond->waiters_count++;
917 LeaveCriticalSection(&cond->waiters_count_lock);
919 /* unlock the mutex associate with the condition */
920 LeaveCriticalSection(&mutex->lock);
921 /* wait for a signal (broadcast or no) */
923 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
925 switch (wait_result) {
927 THROW3(timeout_error, GetLastError(),
928 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
931 THROW0(system_error, GetLastError(),
932 "WaitForMultipleObjects failed, so we cannot wait on the condition");
935 /* we have a signal lock the condition */
936 EnterCriticalSection(&cond->waiters_count_lock);
937 cond->waiters_count--;
939 /* it's the last waiter or it's a broadcast ? */
940 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
941 && (cond->waiters_count == 0));
943 LeaveCriticalSection(&cond->waiters_count_lock);
945 /* yes it's the last waiter or it's a broadcast
946 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
950 if (!ResetEvent(cond->events[BROADCAST]))
951 THROW0(system_error, 0, "ResetEvent failed");
953 /* relock the mutex associated with the condition in accordance with the posix thread specification */
954 EnterCriticalSection(&mutex->lock);
956 /*THROW_UNIMPLEMENTED; */
959 void xbt_os_cond_signal(xbt_os_cond_t cond)
963 EnterCriticalSection(&cond->waiters_count_lock);
964 have_waiters = cond->waiters_count > 0;
965 LeaveCriticalSection(&cond->waiters_count_lock);
968 if (!SetEvent(cond->events[SIGNAL]))
969 THROW0(system_error, 0, "SetEvent failed");
971 xbt_os_thread_yield();
974 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
978 EnterCriticalSection(&cond->waiters_count_lock);
979 have_waiters = cond->waiters_count > 0;
980 LeaveCriticalSection(&cond->waiters_count_lock);
983 SetEvent(cond->events[BROADCAST]);
986 void xbt_os_cond_destroy(xbt_os_cond_t cond)
993 if (!CloseHandle(cond->events[SIGNAL]))
996 if (!CloseHandle(cond->events[BROADCAST]))
999 DeleteCriticalSection(&cond->waiters_count_lock);
1004 THROW0(system_error, 0, "Error while destroying the condition");
1007 typedef struct xbt_os_sem_ {
1010 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1014 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1017 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1021 if (value > INT_MAX)
1022 THROW1(arg_error, value,
1023 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1026 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1028 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1029 THROW1(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1030 strerror(GetLastError()));
1036 InitializeCriticalSection(&(res->value_lock));
1041 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1044 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1047 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1048 THROW1(system_error, GetLastError(),
1049 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1050 EnterCriticalSection(&(sem->value_lock));
1052 LeaveCriticalSection(&(sem->value_lock));
1055 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1059 double end = timeout + xbt_os_time();
1062 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1065 xbt_os_sem_acquire(sem);
1066 } else { /* timeout can be zero <-> try acquire ) */
1069 seconds = (long) floor(end);
1070 milliseconds = (long) ((end - seconds) * 1000);
1071 milliseconds += (seconds * 1000);
1073 switch (WaitForSingleObject(sem->h, milliseconds)) {
1075 EnterCriticalSection(&(sem->value_lock));
1077 LeaveCriticalSection(&(sem->value_lock));
1081 THROW2(timeout_error, GetLastError(),
1082 "semaphore %p wasn't signaled before timeout (%f)", sem,
1087 THROW3(system_error, GetLastError(),
1088 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1089 strerror(GetLastError()));
1094 void xbt_os_sem_release(xbt_os_sem_t sem)
1097 THROW0(arg_error, EINVAL, "Cannot release the NULL semaphore");
1099 if (!ReleaseSemaphore(sem->h, 1, NULL))
1100 THROW1(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1101 strerror(GetLastError()));
1102 EnterCriticalSection(&(sem->value_lock));
1104 LeaveCriticalSection(&(sem->value_lock));
1107 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1110 THROW0(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1112 if (!CloseHandle(sem->h))
1113 THROW1(system_error, GetLastError(), "CloseHandle() failed: %s",
1114 strerror(GetLastError()));
1116 DeleteCriticalSection(&(sem->value_lock));
1122 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1125 THROW0(arg_error, EINVAL,
1126 "Cannot get the value of the NULL semaphore");
1128 EnterCriticalSection(&(sem->value_lock));
1129 *svalue = sem->value;
1130 LeaveCriticalSection(&(sem->value_lock));