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 THROW0(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 THROW0(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 // THROW0(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 THROW0(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 THROW1(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_set_extra_data(void *data)
196 xbt_os_thread_self()->extra_data = data;
199 void *xbt_os_thread_get_extra_data(void)
201 return xbt_os_thread_self()->extra_data;
204 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
209 if ((errcode = pthread_join(thread->t, thread_return)))
210 THROW1(system_error, errcode, "pthread_join failed: %s",
212 xbt_os_thread_free_thread_data(thread);
215 void xbt_os_thread_exit(int *retval)
217 pthread_exit(retval);
220 xbt_os_thread_t xbt_os_thread_self(void)
224 if (!thread_mod_inited)
227 res = pthread_getspecific(xbt_self_thread_key);
232 void xbt_os_thread_detach(xbt_os_thread_t thread)
234 thread->detached = 1;
235 pthread_detach(thread->t);
239 void xbt_os_thread_yield(void)
244 void xbt_os_thread_cancel(xbt_os_thread_t t)
246 pthread_cancel(t->t);
249 /****** mutex related functions ******/
250 typedef struct xbt_os_mutex_ {
251 /* KEEP IT IN SYNC WITH xbt_thread.c */
258 xbt_os_mutex_t xbt_os_mutex_init(void)
260 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
263 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
264 THROW1(system_error, errcode, "pthread_mutex_init() failed: %s",
270 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
274 if ((errcode = pthread_mutex_lock(&(mutex->m))))
275 THROW2(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
276 mutex, strerror(errcode));
280 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
285 xbt_os_mutex_acquire(mutex);
287 } else if (delay == 0) {
288 errcode = pthread_mutex_trylock(&(mutex->m));
294 THROW1(timeout_error, 0, "mutex %p not ready", mutex);
296 THROW2(system_error, errcode,
297 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
304 #ifdef HAVE_MUTEX_TIMEDLOCK
305 struct timespec ts_end;
306 double end = delay + xbt_os_time();
308 ts_end.tv_sec = (time_t) floor(end);
309 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
310 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
312 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
314 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
315 double start = xbt_os_time();
317 errcode = pthread_mutex_trylock(&(mutex->m));
318 if (errcode == EBUSY)
319 xbt_os_thread_yield();
320 } while (errcode == EBUSY && xbt_os_time() - start < delay);
322 if (errcode == EBUSY)
325 #endif /* HAVE_MUTEX_TIMEDLOCK */
332 THROW2(timeout_error, delay,
333 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
336 THROW3(system_error, errcode,
337 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
343 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
347 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
348 THROW2(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
349 mutex, strerror(errcode));
352 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
359 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
360 THROW2(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
361 mutex, strerror(errcode));
365 /***** condition related functions *****/
366 typedef struct xbt_os_cond_ {
367 /* KEEP IT IN SYNC WITH xbt_thread.c */
371 xbt_os_cond_t xbt_os_cond_init(void)
373 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
375 if ((errcode = pthread_cond_init(&(res->c), NULL)))
376 THROW1(system_error, errcode, "pthread_cond_init() failed: %s",
382 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
385 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
386 THROW3(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
387 cond, mutex, strerror(errcode));
391 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
395 struct timespec ts_end;
396 double end = delay + xbt_os_time();
399 xbt_os_cond_wait(cond, mutex);
401 ts_end.tv_sec = (time_t) floor(end);
402 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
403 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
406 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
410 THROW3(timeout_error, errcode,
411 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
414 THROW4(system_error, errcode,
415 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
416 delay, strerror(errcode));
421 void xbt_os_cond_signal(xbt_os_cond_t cond)
424 if ((errcode = pthread_cond_signal(&(cond->c))))
425 THROW2(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
426 cond, strerror(errcode));
429 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
432 if ((errcode = pthread_cond_broadcast(&(cond->c))))
433 THROW2(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
434 cond, strerror(errcode));
437 void xbt_os_cond_destroy(xbt_os_cond_t cond)
444 if ((errcode = pthread_cond_destroy(&(cond->c))))
445 THROW2(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
446 cond, strerror(errcode));
450 void *xbt_os_thread_getparam(void)
452 xbt_os_thread_t t = xbt_os_thread_self();
453 return t ? t->param : NULL;
456 typedef struct xbt_os_sem_ {
457 #ifndef HAVE_SEM_INIT
465 #define SEM_FAILED (-1)
468 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
470 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
472 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
473 * Any attempt to use it leads to ENOSYS (function not implemented).
474 * If such a prehistoric system is detected, do the job with sem_open instead
477 if (sem_init(&(res->s), 0, value) != 0)
478 THROW1(system_error, errno, "sem_init() failed: %s", strerror(errno));
481 #else /* damn, no sem_init(). Reimplement it */
483 xbt_os_mutex_acquire(next_sem_ID_lock);
484 res->name = bprintf("/%d", ++next_sem_ID);
485 xbt_os_mutex_release(next_sem_ID_lock);
487 res->ps = sem_open(res->name, O_CREAT, 0644, value);
488 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
489 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
490 res->name[13] = '\0';
491 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
493 if ((res->ps == (sem_t *) SEM_FAILED))
494 THROW1(system_error, errno, "sem_open() failed: %s", strerror(errno));
496 /* Remove the name from the semaphore namespace: we never join on it */
497 if (sem_unlink(res->name) < 0)
498 THROW1(system_error, errno, "sem_unlink() failed: %s",
506 void xbt_os_sem_acquire(xbt_os_sem_t sem)
509 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
510 if (sem_wait(sem->ps) < 0)
511 THROW1(system_error, errno, "sem_wait() failed: %s", strerror(errno));
514 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
519 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
522 xbt_os_sem_acquire(sem);
523 } else if (delay == 0) {
524 errcode = sem_trywait(sem->ps);
530 THROW1(timeout_error, 0, "semaphore %p not ready", sem);
532 THROW2(system_error, errcode,
533 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
539 struct timespec ts_end;
540 double end = delay + xbt_os_time();
542 ts_end.tv_sec = (time_t) floor(end);
543 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
544 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
545 errcode = sem_timedwait(sem->s, &ts_end);
547 #else /* Okay, reimplement this function then */
548 double start = xbt_os_time();
550 errcode = sem_trywait(sem->ps);
551 if (errcode == EBUSY)
552 xbt_os_thread_yield();
553 } while (errcode == EBUSY && xbt_os_time() - start < delay);
555 if (errcode == EBUSY)
564 THROW2(timeout_error, delay,
565 "semaphore %p wasn't signaled before timeout (%f)", sem,
569 THROW3(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
570 delay, strerror(errcode));
575 void xbt_os_sem_release(xbt_os_sem_t sem)
578 THROW0(arg_error, EINVAL, "Cannot release of the NULL semaphore");
580 if (sem_post(sem->ps) < 0)
581 THROW1(system_error, errno, "sem_post() failed: %s", strerror(errno));
584 void xbt_os_sem_destroy(xbt_os_sem_t sem)
587 THROW0(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
590 if (sem_destroy(sem->ps) < 0)
591 THROW1(system_error, errno, "sem_destroy() failed: %s",
594 if (sem_close(sem->ps) < 0)
595 THROW1(system_error, errno, "sem_close() failed: %s", strerror(errno));
602 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
605 THROW0(arg_error, EINVAL,
606 "Cannot get the value of the NULL semaphore");
608 if (sem_getvalue(&(sem->s), svalue) < 0)
609 THROW1(system_error, errno, "sem_getvalue() failed: %s",
613 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
615 #elif defined(_XBT_WIN32)
619 typedef struct xbt_os_thread_ {
621 HANDLE handle; /* the win thread handle */
622 unsigned long id; /* the win thread id */
623 pvoid_f_pvoid_t start_routine;
628 /* so we can specify the size of the stack of the threads */
629 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
630 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
633 /* the default size of the stack of the threads (in bytes)*/
634 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
636 /* key to the TLS containing the xbt_os_thread_t structure */
637 static unsigned long xbt_self_thread_key;
639 void xbt_os_thread_mod_preinit(void)
641 xbt_self_thread_key = TlsAlloc();
644 void xbt_os_thread_mod_postexit(void)
647 if (!TlsFree(xbt_self_thread_key))
648 THROW0(system_error, (int) GetLastError(),
649 "TlsFree() failed to cleanup the thread submodule");
652 int xbt_os_thread_atfork(void (*prepare)(void),
653 void (*parent)(void), void (*child)(void))
658 static DWORD WINAPI wrapper_start_routine(void *s)
660 xbt_os_thread_t t = (xbt_os_thread_t) s;
663 if (!TlsSetValue(xbt_self_thread_key, t))
664 THROW0(system_error, (int) GetLastError(),
665 "TlsSetValue of data describing the created thread failed");
667 rv = (DWORD *) ((t->start_routine) (t->param));
674 xbt_os_thread_t xbt_os_thread_create(const char *name,
675 pvoid_f_pvoid_t start_routine,
680 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
682 t->name = xbt_strdup(name);
683 t->start_routine = start_routine;
685 t->extra_data = extra_data;
686 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
687 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
688 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
692 THROW0(system_error, (int) GetLastError(), "CreateThread failed");
698 const char *xbt_os_thread_name(xbt_os_thread_t t)
703 const char *xbt_os_thread_self_name(void)
705 xbt_os_thread_t t = xbt_os_thread_self();
706 return t ? t->name : "main";
709 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
712 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
713 THROW0(system_error, (int) GetLastError(),
714 "WaitForSingleObject failed");
718 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
719 THROW0(system_error, (int) GetLastError(),
720 "GetExitCodeThread failed");
723 CloseHandle(thread->handle);
731 void xbt_os_thread_exit(int *retval)
739 void xbt_os_thread_detach(xbt_os_thread_t thread)
745 xbt_os_thread_t xbt_os_thread_self(void)
747 return TlsGetValue(xbt_self_thread_key);
750 void *xbt_os_thread_getparam(void)
752 xbt_os_thread_t t = xbt_os_thread_self();
757 void xbt_os_thread_yield(void)
762 void xbt_os_thread_cancel(xbt_os_thread_t t)
764 if (!TerminateThread(t->handle, 0))
765 THROW0(system_error, (int) GetLastError(), "TerminateThread failed");
768 /****** mutex related functions ******/
769 typedef struct xbt_os_mutex_ {
770 /* KEEP IT IN SYNC WITH xbt_thread.c */
771 CRITICAL_SECTION lock;
774 xbt_os_mutex_t xbt_os_mutex_init(void)
776 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
778 /* initialize the critical section object */
779 InitializeCriticalSection(&(res->lock));
784 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
786 EnterCriticalSection(&mutex->lock);
789 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
794 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
797 LeaveCriticalSection(&mutex->lock);
801 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
807 DeleteCriticalSection(&mutex->lock);
811 /***** condition related functions *****/
812 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
818 typedef struct xbt_os_cond_ {
819 /* KEEP IT IN SYNC WITH xbt_thread.c */
820 HANDLE events[MAX_EVENTS];
822 unsigned int waiters_count; /* the number of waiters */
823 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
826 xbt_os_cond_t xbt_os_cond_init(void)
829 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
831 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
833 /* initialize the critical section object */
834 InitializeCriticalSection(&res->waiters_count_lock);
836 res->waiters_count = 0;
838 /* Create an auto-reset event */
839 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
841 if (!res->events[SIGNAL]) {
842 DeleteCriticalSection(&res->waiters_count_lock);
844 THROW0(system_error, 0, "CreateEvent failed for the signals");
847 /* Create a manual-reset event. */
848 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
850 if (!res->events[BROADCAST]) {
852 DeleteCriticalSection(&res->waiters_count_lock);
853 CloseHandle(res->events[SIGNAL]);
855 THROW0(system_error, 0, "CreateEvent failed for the broadcasts");
861 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
864 unsigned long wait_result;
867 /* lock the threads counter and increment it */
868 EnterCriticalSection(&cond->waiters_count_lock);
869 cond->waiters_count++;
870 LeaveCriticalSection(&cond->waiters_count_lock);
872 /* unlock the mutex associate with the condition */
873 LeaveCriticalSection(&mutex->lock);
875 /* wait for a signal (broadcast or no) */
876 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
878 if (wait_result == WAIT_FAILED)
879 THROW0(system_error, 0,
880 "WaitForMultipleObjects failed, so we cannot wait on the condition");
882 /* we have a signal lock the condition */
883 EnterCriticalSection(&cond->waiters_count_lock);
884 cond->waiters_count--;
886 /* it's the last waiter or it's a broadcast ? */
887 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
888 && (cond->waiters_count == 0));
890 LeaveCriticalSection(&cond->waiters_count_lock);
892 /* yes it's the last waiter or it's a broadcast
893 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
897 if (!ResetEvent(cond->events[BROADCAST]))
898 THROW0(system_error, 0, "ResetEvent failed");
900 /* relock the mutex associated with the condition in accordance with the posix thread specification */
901 EnterCriticalSection(&mutex->lock);
904 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
908 unsigned long wait_result = WAIT_TIMEOUT;
910 unsigned long end = (unsigned long) (delay * 1000);
914 xbt_os_cond_wait(cond, mutex);
916 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
917 &(mutex->lock), end);
919 /* lock the threads counter and increment it */
920 EnterCriticalSection(&cond->waiters_count_lock);
921 cond->waiters_count++;
922 LeaveCriticalSection(&cond->waiters_count_lock);
924 /* unlock the mutex associate with the condition */
925 LeaveCriticalSection(&mutex->lock);
926 /* wait for a signal (broadcast or no) */
928 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
930 switch (wait_result) {
932 THROW3(timeout_error, GetLastError(),
933 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
936 THROW0(system_error, GetLastError(),
937 "WaitForMultipleObjects failed, so we cannot wait on the condition");
940 /* we have a signal lock the condition */
941 EnterCriticalSection(&cond->waiters_count_lock);
942 cond->waiters_count--;
944 /* it's the last waiter or it's a broadcast ? */
945 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
946 && (cond->waiters_count == 0));
948 LeaveCriticalSection(&cond->waiters_count_lock);
950 /* yes it's the last waiter or it's a broadcast
951 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
955 if (!ResetEvent(cond->events[BROADCAST]))
956 THROW0(system_error, 0, "ResetEvent failed");
958 /* relock the mutex associated with the condition in accordance with the posix thread specification */
959 EnterCriticalSection(&mutex->lock);
961 /*THROW_UNIMPLEMENTED; */
964 void xbt_os_cond_signal(xbt_os_cond_t cond)
968 EnterCriticalSection(&cond->waiters_count_lock);
969 have_waiters = cond->waiters_count > 0;
970 LeaveCriticalSection(&cond->waiters_count_lock);
973 if (!SetEvent(cond->events[SIGNAL]))
974 THROW0(system_error, 0, "SetEvent failed");
976 xbt_os_thread_yield();
979 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
983 EnterCriticalSection(&cond->waiters_count_lock);
984 have_waiters = cond->waiters_count > 0;
985 LeaveCriticalSection(&cond->waiters_count_lock);
988 SetEvent(cond->events[BROADCAST]);
991 void xbt_os_cond_destroy(xbt_os_cond_t cond)
998 if (!CloseHandle(cond->events[SIGNAL]))
1001 if (!CloseHandle(cond->events[BROADCAST]))
1004 DeleteCriticalSection(&cond->waiters_count_lock);
1009 THROW0(system_error, 0, "Error while destroying the condition");
1012 typedef struct xbt_os_sem_ {
1015 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1019 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1022 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1026 if (value > INT_MAX)
1027 THROW1(arg_error, value,
1028 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1031 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1033 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1034 THROW1(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1035 strerror(GetLastError()));
1041 InitializeCriticalSection(&(res->value_lock));
1046 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1049 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1052 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1053 THROW1(system_error, GetLastError(),
1054 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1055 EnterCriticalSection(&(sem->value_lock));
1057 LeaveCriticalSection(&(sem->value_lock));
1060 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1064 double end = timeout + xbt_os_time();
1067 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1070 xbt_os_sem_acquire(sem);
1071 } else { /* timeout can be zero <-> try acquire ) */
1074 seconds = (long) floor(end);
1075 milliseconds = (long) ((end - seconds) * 1000);
1076 milliseconds += (seconds * 1000);
1078 switch (WaitForSingleObject(sem->h, milliseconds)) {
1080 EnterCriticalSection(&(sem->value_lock));
1082 LeaveCriticalSection(&(sem->value_lock));
1086 THROW2(timeout_error, GetLastError(),
1087 "semaphore %p wasn't signaled before timeout (%f)", sem,
1092 THROW3(system_error, GetLastError(),
1093 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1094 strerror(GetLastError()));
1099 void xbt_os_sem_release(xbt_os_sem_t sem)
1102 THROW0(arg_error, EINVAL, "Cannot release the NULL semaphore");
1104 if (!ReleaseSemaphore(sem->h, 1, NULL))
1105 THROW1(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1106 strerror(GetLastError()));
1107 EnterCriticalSection(&(sem->value_lock));
1109 LeaveCriticalSection(&(sem->value_lock));
1112 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1115 THROW0(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1117 if (!CloseHandle(sem->h))
1118 THROW1(system_error, GetLastError(), "CloseHandle() failed: %s",
1119 strerror(GetLastError()));
1121 DeleteCriticalSection(&(sem->value_lock));
1127 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1130 THROW0(arg_error, EINVAL,
1131 "Cannot get the value of the NULL semaphore");
1133 EnterCriticalSection(&(sem->value_lock));
1134 *svalue = sem->value;
1135 LeaveCriticalSection(&(sem->value_lock));