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_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 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_detach(xbt_os_thread_t thread)
224 thread->detached = 1;
225 pthread_detach(thread->t);
229 void xbt_os_thread_yield(void)
234 void xbt_os_thread_cancel(xbt_os_thread_t t)
236 pthread_cancel(t->t);
239 /****** mutex related functions ******/
240 typedef struct xbt_os_mutex_ {
241 /* KEEP IT IN SYNC WITH xbt_thread.c */
248 xbt_os_mutex_t xbt_os_mutex_init(void)
250 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
253 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
254 THROW1(system_error, errcode, "pthread_mutex_init() failed: %s",
260 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
264 if ((errcode = pthread_mutex_lock(&(mutex->m))))
265 THROW2(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
266 mutex, strerror(errcode));
270 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
275 xbt_os_mutex_acquire(mutex);
277 } else if (delay == 0) {
278 errcode = pthread_mutex_trylock(&(mutex->m));
284 THROW1(timeout_error, 0, "mutex %p not ready", mutex);
286 THROW2(system_error, errcode,
287 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
294 #ifdef HAVE_MUTEX_TIMEDLOCK
295 struct timespec ts_end;
296 double end = delay + xbt_os_time();
298 ts_end.tv_sec = (time_t) floor(end);
299 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
300 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
302 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
304 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
305 double start = xbt_os_time();
307 errcode = pthread_mutex_trylock(&(mutex->m));
308 if (errcode == EBUSY)
309 xbt_os_thread_yield();
310 } while (errcode == EBUSY && xbt_os_time() - start < delay);
312 if (errcode == EBUSY)
315 #endif /* HAVE_MUTEX_TIMEDLOCK */
322 THROW2(timeout_error, delay,
323 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
326 THROW3(system_error, errcode,
327 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
333 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
337 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
338 THROW2(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
339 mutex, strerror(errcode));
342 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
349 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
350 THROW2(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
351 mutex, strerror(errcode));
355 /***** condition related functions *****/
356 typedef struct xbt_os_cond_ {
357 /* KEEP IT IN SYNC WITH xbt_thread.c */
361 xbt_os_cond_t xbt_os_cond_init(void)
363 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
365 if ((errcode = pthread_cond_init(&(res->c), NULL)))
366 THROW1(system_error, errcode, "pthread_cond_init() failed: %s",
372 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
375 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
376 THROW3(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
377 cond, mutex, strerror(errcode));
381 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
385 struct timespec ts_end;
386 double end = delay + xbt_os_time();
389 xbt_os_cond_wait(cond, mutex);
391 ts_end.tv_sec = (time_t) floor(end);
392 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
393 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
396 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
400 THROW3(timeout_error, errcode,
401 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
404 THROW4(system_error, errcode,
405 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
406 delay, strerror(errcode));
411 void xbt_os_cond_signal(xbt_os_cond_t cond)
414 if ((errcode = pthread_cond_signal(&(cond->c))))
415 THROW2(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
416 cond, strerror(errcode));
419 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
422 if ((errcode = pthread_cond_broadcast(&(cond->c))))
423 THROW2(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
424 cond, strerror(errcode));
427 void xbt_os_cond_destroy(xbt_os_cond_t cond)
434 if ((errcode = pthread_cond_destroy(&(cond->c))))
435 THROW2(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
436 cond, strerror(errcode));
440 void *xbt_os_thread_getparam(void)
442 xbt_os_thread_t t = xbt_os_thread_self();
443 return t ? t->param : NULL;
446 typedef struct xbt_os_sem_ {
447 #ifndef HAVE_SEM_INIT
455 #define SEM_FAILED (-1)
458 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
460 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
462 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
463 * Any attempt to use it leads to ENOSYS (function not implemented).
464 * If such a prehistoric system is detected, do the job with sem_open instead
467 if (sem_init(&(res->s), 0, value) != 0)
468 THROW1(system_error, errno, "sem_init() failed: %s", strerror(errno));
471 #else /* damn, no sem_init(). Reimplement it */
473 xbt_os_mutex_acquire(next_sem_ID_lock);
474 res->name = bprintf("/%d", ++next_sem_ID);
475 xbt_os_mutex_release(next_sem_ID_lock);
477 res->ps = sem_open(res->name, O_CREAT, 0644, value);
478 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
479 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
480 res->name[13] = '\0';
481 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
483 if ((res->ps == (sem_t *) SEM_FAILED))
484 THROW1(system_error, errno, "sem_open() failed: %s", strerror(errno));
486 /* Remove the name from the semaphore namespace: we never join on it */
487 if (sem_unlink(res->name) < 0)
488 THROW1(system_error, errno, "sem_unlink() failed: %s",
496 void xbt_os_sem_acquire(xbt_os_sem_t sem)
499 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
500 if (sem_wait(sem->ps) < 0)
501 THROW1(system_error, errno, "sem_wait() failed: %s", strerror(errno));
504 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
509 THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
512 xbt_os_sem_acquire(sem);
513 } else if (delay == 0) {
514 errcode = sem_trywait(sem->ps);
520 THROW1(timeout_error, 0, "semaphore %p not ready", sem);
522 THROW2(system_error, errcode,
523 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
529 struct timespec ts_end;
530 double end = delay + xbt_os_time();
532 ts_end.tv_sec = (time_t) floor(end);
533 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
534 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
535 errcode = sem_timedwait(sem->s, &ts_end);
537 #else /* Okay, reimplement this function then */
538 double start = xbt_os_time();
540 errcode = sem_trywait(sem->ps);
541 if (errcode == EBUSY)
542 xbt_os_thread_yield();
543 } while (errcode == EBUSY && xbt_os_time() - start < delay);
545 if (errcode == EBUSY)
554 THROW2(timeout_error, delay,
555 "semaphore %p wasn't signaled before timeout (%f)", sem,
559 THROW3(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
560 delay, strerror(errcode));
565 void xbt_os_sem_release(xbt_os_sem_t sem)
568 THROW0(arg_error, EINVAL, "Cannot release of the NULL semaphore");
570 if (sem_post(sem->ps) < 0)
571 THROW1(system_error, errno, "sem_post() failed: %s", strerror(errno));
574 void xbt_os_sem_destroy(xbt_os_sem_t sem)
577 THROW0(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
580 if (sem_destroy(sem->ps) < 0)
581 THROW1(system_error, errno, "sem_destroy() failed: %s",
584 if (sem_close(sem->ps) < 0)
585 THROW1(system_error, errno, "sem_close() failed: %s", strerror(errno));
592 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
595 THROW0(arg_error, EINVAL,
596 "Cannot get the value of the NULL semaphore");
598 if (sem_getvalue(&(sem->s), svalue) < 0)
599 THROW1(system_error, errno, "sem_getvalue() failed: %s",
603 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
605 #elif defined(_XBT_WIN32)
609 typedef struct xbt_os_thread_ {
611 HANDLE handle; /* the win thread handle */
612 unsigned long id; /* the win thread id */
613 pvoid_f_pvoid_t start_routine;
618 /* so we can specify the size of the stack of the threads */
619 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
620 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
623 /* the default size of the stack of the threads (in bytes)*/
624 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
626 /* key to the TLS containing the xbt_os_thread_t structure */
627 static unsigned long xbt_self_thread_key;
629 void xbt_os_thread_mod_preinit(void)
631 xbt_self_thread_key = TlsAlloc();
634 void xbt_os_thread_mod_postexit(void)
637 if (!TlsFree(xbt_self_thread_key))
638 THROW0(system_error, (int) GetLastError(),
639 "TlsFree() failed to cleanup the thread submodule");
642 int xbt_os_thread_atfork(void (*prepare)(void),
643 void (*parent)(void), void (*child)(void))
648 static DWORD WINAPI wrapper_start_routine(void *s)
650 xbt_os_thread_t t = (xbt_os_thread_t) s;
653 if (!TlsSetValue(xbt_self_thread_key, t))
654 THROW0(system_error, (int) GetLastError(),
655 "TlsSetValue of data describing the created thread failed");
657 rv = (DWORD *) ((t->start_routine) (t->param));
664 xbt_os_thread_t xbt_os_thread_create(const char *name,
665 pvoid_f_pvoid_t start_routine,
670 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
672 t->name = xbt_strdup(name);
673 t->start_routine = start_routine;
675 t->extra_data = extra_data;
676 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
677 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
678 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
682 THROW0(system_error, (int) GetLastError(), "CreateThread failed");
688 const char *xbt_os_thread_name(xbt_os_thread_t t)
693 const char *xbt_os_thread_self_name(void)
695 xbt_os_thread_t t = xbt_os_thread_self();
696 return t ? t->name : "main";
699 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
702 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
703 THROW0(system_error, (int) GetLastError(),
704 "WaitForSingleObject failed");
708 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
709 THROW0(system_error, (int) GetLastError(),
710 "GetExitCodeThread failed");
713 CloseHandle(thread->handle);
721 void xbt_os_thread_exit(int *retval)
729 void xbt_os_thread_detach(xbt_os_thread_t thread)
735 xbt_os_thread_t xbt_os_thread_self(void)
737 return TlsGetValue(xbt_self_thread_key);
740 void *xbt_os_thread_getparam(void)
742 xbt_os_thread_t t = xbt_os_thread_self();
747 void xbt_os_thread_yield(void)
752 void xbt_os_thread_cancel(xbt_os_thread_t t)
754 if (!TerminateThread(t->handle, 0))
755 THROW0(system_error, (int) GetLastError(), "TerminateThread failed");
758 /****** mutex related functions ******/
759 typedef struct xbt_os_mutex_ {
760 /* KEEP IT IN SYNC WITH xbt_thread.c */
761 CRITICAL_SECTION lock;
764 xbt_os_mutex_t xbt_os_mutex_init(void)
766 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
768 /* initialize the critical section object */
769 InitializeCriticalSection(&(res->lock));
774 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
776 EnterCriticalSection(&mutex->lock);
779 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
784 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
787 LeaveCriticalSection(&mutex->lock);
791 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
797 DeleteCriticalSection(&mutex->lock);
801 /***** condition related functions *****/
802 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
808 typedef struct xbt_os_cond_ {
809 /* KEEP IT IN SYNC WITH xbt_thread.c */
810 HANDLE events[MAX_EVENTS];
812 unsigned int waiters_count; /* the number of waiters */
813 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
816 xbt_os_cond_t xbt_os_cond_init(void)
819 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
821 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
823 /* initialize the critical section object */
824 InitializeCriticalSection(&res->waiters_count_lock);
826 res->waiters_count = 0;
828 /* Create an auto-reset event */
829 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
831 if (!res->events[SIGNAL]) {
832 DeleteCriticalSection(&res->waiters_count_lock);
834 THROW0(system_error, 0, "CreateEvent failed for the signals");
837 /* Create a manual-reset event. */
838 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
840 if (!res->events[BROADCAST]) {
842 DeleteCriticalSection(&res->waiters_count_lock);
843 CloseHandle(res->events[SIGNAL]);
845 THROW0(system_error, 0, "CreateEvent failed for the broadcasts");
851 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
854 unsigned long wait_result;
857 /* lock the threads counter and increment it */
858 EnterCriticalSection(&cond->waiters_count_lock);
859 cond->waiters_count++;
860 LeaveCriticalSection(&cond->waiters_count_lock);
862 /* unlock the mutex associate with the condition */
863 LeaveCriticalSection(&mutex->lock);
865 /* wait for a signal (broadcast or no) */
866 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
868 if (wait_result == WAIT_FAILED)
869 THROW0(system_error, 0,
870 "WaitForMultipleObjects failed, so we cannot wait on the condition");
872 /* we have a signal lock the condition */
873 EnterCriticalSection(&cond->waiters_count_lock);
874 cond->waiters_count--;
876 /* it's the last waiter or it's a broadcast ? */
877 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
878 && (cond->waiters_count == 0));
880 LeaveCriticalSection(&cond->waiters_count_lock);
882 /* yes it's the last waiter or it's a broadcast
883 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
887 if (!ResetEvent(cond->events[BROADCAST]))
888 THROW0(system_error, 0, "ResetEvent failed");
890 /* relock the mutex associated with the condition in accordance with the posix thread specification */
891 EnterCriticalSection(&mutex->lock);
894 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
898 unsigned long wait_result = WAIT_TIMEOUT;
900 unsigned long end = (unsigned long) (delay * 1000);
904 xbt_os_cond_wait(cond, mutex);
906 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
907 &(mutex->lock), end);
909 /* lock the threads counter and increment it */
910 EnterCriticalSection(&cond->waiters_count_lock);
911 cond->waiters_count++;
912 LeaveCriticalSection(&cond->waiters_count_lock);
914 /* unlock the mutex associate with the condition */
915 LeaveCriticalSection(&mutex->lock);
916 /* wait for a signal (broadcast or no) */
918 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
920 switch (wait_result) {
922 THROW3(timeout_error, GetLastError(),
923 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
926 THROW0(system_error, GetLastError(),
927 "WaitForMultipleObjects failed, so we cannot wait on the condition");
930 /* we have a signal lock the condition */
931 EnterCriticalSection(&cond->waiters_count_lock);
932 cond->waiters_count--;
934 /* it's the last waiter or it's a broadcast ? */
935 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
936 && (cond->waiters_count == 0));
938 LeaveCriticalSection(&cond->waiters_count_lock);
940 /* yes it's the last waiter or it's a broadcast
941 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
945 if (!ResetEvent(cond->events[BROADCAST]))
946 THROW0(system_error, 0, "ResetEvent failed");
948 /* relock the mutex associated with the condition in accordance with the posix thread specification */
949 EnterCriticalSection(&mutex->lock);
951 /*THROW_UNIMPLEMENTED; */
954 void xbt_os_cond_signal(xbt_os_cond_t cond)
958 EnterCriticalSection(&cond->waiters_count_lock);
959 have_waiters = cond->waiters_count > 0;
960 LeaveCriticalSection(&cond->waiters_count_lock);
963 if (!SetEvent(cond->events[SIGNAL]))
964 THROW0(system_error, 0, "SetEvent failed");
966 xbt_os_thread_yield();
969 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
973 EnterCriticalSection(&cond->waiters_count_lock);
974 have_waiters = cond->waiters_count > 0;
975 LeaveCriticalSection(&cond->waiters_count_lock);
978 SetEvent(cond->events[BROADCAST]);
981 void xbt_os_cond_destroy(xbt_os_cond_t cond)
988 if (!CloseHandle(cond->events[SIGNAL]))
991 if (!CloseHandle(cond->events[BROADCAST]))
994 DeleteCriticalSection(&cond->waiters_count_lock);
999 THROW0(system_error, 0, "Error while destroying the condition");
1002 typedef struct xbt_os_sem_ {
1005 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1009 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1012 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1016 if (value > INT_MAX)
1017 THROW1(arg_error, value,
1018 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1021 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1023 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1024 THROW1(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1025 strerror(GetLastError()));
1031 InitializeCriticalSection(&(res->value_lock));
1036 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1039 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1042 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1043 THROW1(system_error, GetLastError(),
1044 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1045 EnterCriticalSection(&(sem->value_lock));
1047 LeaveCriticalSection(&(sem->value_lock));
1050 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1054 double end = timeout + xbt_os_time();
1057 THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1060 xbt_os_sem_acquire(sem);
1061 } else { /* timeout can be zero <-> try acquire ) */
1064 seconds = (long) floor(end);
1065 milliseconds = (long) ((end - seconds) * 1000);
1066 milliseconds += (seconds * 1000);
1068 switch (WaitForSingleObject(sem->h, milliseconds)) {
1070 EnterCriticalSection(&(sem->value_lock));
1072 LeaveCriticalSection(&(sem->value_lock));
1076 THROW2(timeout_error, GetLastError(),
1077 "semaphore %p wasn't signaled before timeout (%f)", sem,
1082 THROW3(system_error, GetLastError(),
1083 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1084 strerror(GetLastError()));
1089 void xbt_os_sem_release(xbt_os_sem_t sem)
1092 THROW0(arg_error, EINVAL, "Cannot release the NULL semaphore");
1094 if (!ReleaseSemaphore(sem->h, 1, NULL))
1095 THROW1(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1096 strerror(GetLastError()));
1097 EnterCriticalSection(&(sem->value_lock));
1099 LeaveCriticalSection(&(sem->value_lock));
1102 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1105 THROW0(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1107 if (!CloseHandle(sem->h))
1108 THROW1(system_error, GetLastError(), "CloseHandle() failed: %s",
1109 strerror(GetLastError()));
1111 DeleteCriticalSection(&(sem->value_lock));
1117 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1120 THROW0(arg_error, EINVAL,
1121 "Cannot get the value of the NULL semaphore");
1123 EnterCriticalSection(&(sem->value_lock));
1124 *svalue = sem->value;
1125 LeaveCriticalSection(&(sem->value_lock));
1131 void xbt_os_thread_set_extra_data(void *data)
1133 xbt_os_thread_self()->extra_data = data;
1136 void *xbt_os_thread_get_extra_data(void)
1138 return xbt_os_thread_self()->extra_data;