1 /* xbt_os_thread -- portability layer over the pthread API */
2 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD */
3 /* in SG, when using CONTEXT_UCONTEXT, xbt_os_thread_stub is used instead */
5 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
6 * All rights reserved. */
8 /* This program is free software; you can redistribute it and/or modify it
9 * under the terms of the license (GNU LGPL) which comes with this package. */
11 #include "gras_config.h"
12 #include "xbt/sysdep.h"
14 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
16 #include "xbt/xbt_os_time.h" /* Portable time facilities */
17 #include "xbt/xbt_os_thread.h" /* This module */
18 #include "xbt_modinter.h" /* Initialization/finalization of this module */
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
21 "Synchronization mechanism (OS-level)");
23 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
27 #include <semaphore.h>
29 #ifdef HAVE_MUTEX_TIMEDLOCK
30 /* redefine the function header since we fail to get this from system headers on amd (at least) */
31 int pthread_mutex_timedlock(pthread_mutex_t * mutex,
32 const struct timespec *abs_timeout);
36 /* use named sempahore when sem_init() does not work */
38 static int next_sem_ID = 0;
39 static xbt_os_mutex_t next_sem_ID_lock;
42 typedef struct xbt_os_thread_ {
47 pvoid_f_pvoid_t start_routine;
48 xbt_running_ctx_t *running_ctx;
51 static xbt_os_thread_t main_thread = NULL;
53 /* thread-specific data containing the xbt_os_thread_t structure */
54 static pthread_key_t xbt_self_thread_key;
55 static int thread_mod_inited = 0;
57 /* frees the xbt_os_thread_t corresponding to the current thread */
58 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
60 if (thread == main_thread) /* just killed main thread */
63 free(thread->running_ctx);
68 /* callback: context fetching */
69 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
71 return xbt_os_thread_self()->running_ctx;
74 /* callback: termination */
75 static void _os_thread_ex_terminate(xbt_ex_t * e)
80 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
83 void xbt_os_thread_mod_preinit(void)
87 if (thread_mod_inited)
90 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
91 THROWF(system_error, errcode,
92 "pthread_key_create failed for xbt_self_thread_key");
94 main_thread = xbt_new(s_xbt_os_thread_t, 1);
95 main_thread->name = (char *) "main";
96 main_thread->start_routine = NULL;
97 main_thread->param = NULL;
98 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
99 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
101 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
102 THROWF(system_error, errcode,
103 "pthread_setspecific failed for xbt_self_thread_key");
106 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
107 __xbt_ex_terminate = _os_thread_ex_terminate;
109 thread_mod_inited = 1;
111 #ifndef HAVE_SEM_INIT
112 next_sem_ID_lock = xbt_os_mutex_init();
117 void xbt_os_thread_mod_postexit(void)
119 /* FIXME: don't try to free our key on shutdown.
120 Valgrind detects no leak if we don't, and whine if we try to */
123 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
124 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
125 free(main_thread->running_ctx);
128 thread_mod_inited = 0;
129 #ifndef HAVE_SEM_INIT
130 xbt_os_mutex_destroy(next_sem_ID_lock);
133 /* Restore the default exception setup */
134 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
135 __xbt_ex_terminate = &__xbt_ex_terminate_default;
138 int xbt_os_thread_atfork(void (*prepare)(void),
139 void (*parent)(void), void (*child)(void))
141 return pthread_atfork(prepare, parent, child);
144 static void *wrapper_start_routine(void *s)
146 xbt_os_thread_t t = s;
149 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
150 THROWF(system_error, errcode,
151 "pthread_setspecific failed for xbt_self_thread_key");
153 void *res = (*(t->start_routine)) (t->param);
155 xbt_os_thread_free_thread_data(t);
159 xbt_os_thread_t xbt_os_thread_create(const char *name,
160 pvoid_f_pvoid_t start_routine,
166 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
167 res_thread->detached = 0;
168 res_thread->name = xbt_strdup(name);
169 res_thread->start_routine = start_routine;
170 res_thread->param = param;
171 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
172 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
173 res_thread->extra_data = extra_data;
175 if ((errcode = pthread_create(&(res_thread->t), NULL,
176 wrapper_start_routine, res_thread)))
177 THROWF(system_error, errcode,
178 "pthread_create failed: %s", strerror(errcode));
183 const char *xbt_os_thread_name(xbt_os_thread_t t)
188 const char *xbt_os_thread_self_name(void)
190 xbt_os_thread_t me = xbt_os_thread_self();
191 return me ? me->name : "main";
194 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
199 if ((errcode = pthread_join(thread->t, thread_return)))
200 THROWF(system_error, errcode, "pthread_join failed: %s",
202 xbt_os_thread_free_thread_data(thread);
205 void xbt_os_thread_exit(int *retval)
207 pthread_exit(retval);
210 xbt_os_thread_t xbt_os_thread_self(void)
214 if (!thread_mod_inited)
217 res = pthread_getspecific(xbt_self_thread_key);
222 void xbt_os_thread_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 */
245 typedef struct xbt_os_rmutex_ {
246 xbt_os_mutex_t mutex;
247 xbt_os_thread_t owner;
254 xbt_os_mutex_t xbt_os_mutex_init(void)
256 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
259 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
260 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
266 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
270 if ((errcode = pthread_mutex_lock(&(mutex->m))))
271 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
272 mutex, strerror(errcode));
276 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
281 xbt_os_mutex_acquire(mutex);
283 } else if (delay == 0) {
284 errcode = pthread_mutex_trylock(&(mutex->m));
290 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
292 THROWF(system_error, errcode,
293 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
300 #ifdef HAVE_MUTEX_TIMEDLOCK
301 struct timespec ts_end;
302 double end = delay + xbt_os_time();
304 ts_end.tv_sec = (time_t) floor(end);
305 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
306 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
308 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
310 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
311 double start = xbt_os_time();
313 errcode = pthread_mutex_trylock(&(mutex->m));
314 if (errcode == EBUSY)
315 xbt_os_thread_yield();
316 } while (errcode == EBUSY && xbt_os_time() - start < delay);
318 if (errcode == EBUSY)
321 #endif /* HAVE_MUTEX_TIMEDLOCK */
328 THROWF(timeout_error, delay,
329 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
332 THROWF(system_error, errcode,
333 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
339 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
343 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
344 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
345 mutex, strerror(errcode));
348 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
355 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
356 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
357 mutex, strerror(errcode));
361 xbt_os_rmutex_t xbt_os_rmutex_init(void)
363 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 0);
364 rmutex->mutex = xbt_os_mutex_init();
365 rmutex->owner = NULL;
370 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
372 xbt_os_thread_t self = xbt_os_thread_self();
373 xbt_assert(self != NULL, "Cannot get my own thread object (is the thread module initialized?)");
375 if (self != rmutex->owner) {
376 xbt_os_mutex_acquire(rmutex->mutex);
377 rmutex->owner = self;
384 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
386 xbt_assert(rmutex->owner == xbt_os_thread_self());
388 if (--rmutex->count == 0) {
389 rmutex->owner = NULL;
390 xbt_os_mutex_release(rmutex->mutex);
394 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
396 xbt_os_mutex_destroy(rmutex->mutex);
400 /***** condition related functions *****/
401 typedef struct xbt_os_cond_ {
402 /* KEEP IT IN SYNC WITH xbt_thread.c */
406 xbt_os_cond_t xbt_os_cond_init(void)
408 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
410 if ((errcode = pthread_cond_init(&(res->c), NULL)))
411 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
417 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
420 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
421 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
422 cond, mutex, strerror(errcode));
426 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
430 struct timespec ts_end;
431 double end = delay + xbt_os_time();
434 xbt_os_cond_wait(cond, mutex);
436 ts_end.tv_sec = (time_t) floor(end);
437 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
438 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
441 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
445 THROWF(timeout_error, errcode,
446 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
449 THROWF(system_error, errcode,
450 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
451 delay, strerror(errcode));
456 void xbt_os_cond_signal(xbt_os_cond_t cond)
459 if ((errcode = pthread_cond_signal(&(cond->c))))
460 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
461 cond, strerror(errcode));
464 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
467 if ((errcode = pthread_cond_broadcast(&(cond->c))))
468 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
469 cond, strerror(errcode));
472 void xbt_os_cond_destroy(xbt_os_cond_t cond)
479 if ((errcode = pthread_cond_destroy(&(cond->c))))
480 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
481 cond, strerror(errcode));
485 void *xbt_os_thread_getparam(void)
487 xbt_os_thread_t t = xbt_os_thread_self();
488 return t ? t->param : NULL;
491 typedef struct xbt_os_sem_ {
492 #ifndef HAVE_SEM_INIT
500 #define SEM_FAILED (-1)
503 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
505 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
507 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
508 * Any attempt to use it leads to ENOSYS (function not implemented).
509 * If such a prehistoric system is detected, do the job with sem_open instead
512 if (sem_init(&(res->s), 0, value) != 0)
513 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
516 #else /* damn, no sem_init(). Reimplement it */
518 xbt_os_mutex_acquire(next_sem_ID_lock);
519 res->name = bprintf("/%d", ++next_sem_ID);
520 xbt_os_mutex_release(next_sem_ID_lock);
522 res->ps = sem_open(res->name, O_CREAT, 0644, value);
523 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
524 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
525 res->name[13] = '\0';
526 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
528 if ((res->ps == (sem_t *) SEM_FAILED))
529 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
531 /* Remove the name from the semaphore namespace: we never join on it */
532 if (sem_unlink(res->name) < 0)
533 THROWF(system_error, errno, "sem_unlink() failed: %s",
541 void xbt_os_sem_acquire(xbt_os_sem_t sem)
544 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
545 if (sem_wait(sem->ps) < 0)
546 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
549 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
554 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
557 xbt_os_sem_acquire(sem);
558 } else if (delay == 0) {
559 errcode = sem_trywait(sem->ps);
565 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
567 THROWF(system_error, errcode,
568 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
574 struct timespec ts_end;
575 double end = delay + xbt_os_time();
577 ts_end.tv_sec = (time_t) floor(end);
578 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
579 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
580 errcode = sem_timedwait(sem->s, &ts_end);
582 #else /* Okay, reimplement this function then */
583 double start = xbt_os_time();
585 errcode = sem_trywait(sem->ps);
586 if (errcode == EBUSY)
587 xbt_os_thread_yield();
588 } while (errcode == EBUSY && xbt_os_time() - start < delay);
590 if (errcode == EBUSY)
599 THROWF(timeout_error, delay,
600 "semaphore %p wasn't signaled before timeout (%f)", sem,
604 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
605 delay, strerror(errcode));
610 void xbt_os_sem_release(xbt_os_sem_t sem)
613 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
615 if (sem_post(sem->ps) < 0)
616 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
619 void xbt_os_sem_destroy(xbt_os_sem_t sem)
622 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
625 if (sem_destroy(sem->ps) < 0)
626 THROWF(system_error, errno, "sem_destroy() failed: %s",
629 if (sem_close(sem->ps) < 0)
630 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
637 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
640 THROWF(arg_error, EINVAL,
641 "Cannot get the value of the NULL semaphore");
643 if (sem_getvalue(&(sem->s), svalue) < 0)
644 THROWF(system_error, errno, "sem_getvalue() failed: %s",
648 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
650 #elif defined(_XBT_WIN32)
654 typedef struct xbt_os_thread_ {
656 HANDLE handle; /* the win thread handle */
657 unsigned long id; /* the win thread id */
658 pvoid_f_pvoid_t start_routine;
663 /* so we can specify the size of the stack of the threads */
664 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
665 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
668 /* the default size of the stack of the threads (in bytes)*/
669 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
671 /* key to the TLS containing the xbt_os_thread_t structure */
672 static unsigned long xbt_self_thread_key;
674 void xbt_os_thread_mod_preinit(void)
676 xbt_self_thread_key = TlsAlloc();
679 void xbt_os_thread_mod_postexit(void)
682 if (!TlsFree(xbt_self_thread_key))
683 THROWF(system_error, (int) GetLastError(),
684 "TlsFree() failed to cleanup the thread submodule");
687 int xbt_os_thread_atfork(void (*prepare)(void),
688 void (*parent)(void), void (*child)(void))
693 static DWORD WINAPI wrapper_start_routine(void *s)
695 xbt_os_thread_t t = (xbt_os_thread_t) s;
698 if (!TlsSetValue(xbt_self_thread_key, t))
699 THROWF(system_error, (int) GetLastError(),
700 "TlsSetValue of data describing the created thread failed");
702 rv = (DWORD *) ((t->start_routine) (t->param));
709 xbt_os_thread_t xbt_os_thread_create(const char *name,
710 pvoid_f_pvoid_t start_routine,
715 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
717 t->name = xbt_strdup(name);
718 t->start_routine = start_routine;
720 t->extra_data = extra_data;
721 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
722 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
723 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
727 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
733 const char *xbt_os_thread_name(xbt_os_thread_t t)
738 const char *xbt_os_thread_self_name(void)
740 xbt_os_thread_t t = xbt_os_thread_self();
741 return t ? t->name : "main";
744 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
747 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
748 THROWF(system_error, (int) GetLastError(),
749 "WaitForSingleObject failed");
753 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
754 THROWF(system_error, (int) GetLastError(),
755 "GetExitCodeThread failed");
758 CloseHandle(thread->handle);
766 void xbt_os_thread_exit(int *retval)
774 void xbt_os_thread_detach(xbt_os_thread_t thread)
780 xbt_os_thread_t xbt_os_thread_self(void)
782 return TlsGetValue(xbt_self_thread_key);
785 void *xbt_os_thread_getparam(void)
787 xbt_os_thread_t t = xbt_os_thread_self();
792 void xbt_os_thread_yield(void)
797 void xbt_os_thread_cancel(xbt_os_thread_t t)
799 if (!TerminateThread(t->handle, 0))
800 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
803 /****** mutex related functions ******/
804 typedef struct xbt_os_mutex_ {
805 /* KEEP IT IN SYNC WITH xbt_thread.c */
806 CRITICAL_SECTION lock;
809 xbt_os_mutex_t xbt_os_mutex_init(void)
811 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
813 /* initialize the critical section object */
814 InitializeCriticalSection(&(res->lock));
819 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
821 EnterCriticalSection(&mutex->lock);
824 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
829 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
832 LeaveCriticalSection(&mutex->lock);
836 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
842 DeleteCriticalSection(&mutex->lock);
846 /***** condition related functions *****/
847 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
853 typedef struct xbt_os_cond_ {
854 /* KEEP IT IN SYNC WITH xbt_thread.c */
855 HANDLE events[MAX_EVENTS];
857 unsigned int waiters_count; /* the number of waiters */
858 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
861 xbt_os_cond_t xbt_os_cond_init(void)
864 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
866 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
868 /* initialize the critical section object */
869 InitializeCriticalSection(&res->waiters_count_lock);
871 res->waiters_count = 0;
873 /* Create an auto-reset event */
874 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
876 if (!res->events[SIGNAL]) {
877 DeleteCriticalSection(&res->waiters_count_lock);
879 THROWF(system_error, 0, "CreateEvent failed for the signals");
882 /* Create a manual-reset event. */
883 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
885 if (!res->events[BROADCAST]) {
887 DeleteCriticalSection(&res->waiters_count_lock);
888 CloseHandle(res->events[SIGNAL]);
890 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
896 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
899 unsigned long wait_result;
902 /* lock the threads counter and increment it */
903 EnterCriticalSection(&cond->waiters_count_lock);
904 cond->waiters_count++;
905 LeaveCriticalSection(&cond->waiters_count_lock);
907 /* unlock the mutex associate with the condition */
908 LeaveCriticalSection(&mutex->lock);
910 /* wait for a signal (broadcast or no) */
911 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
913 if (wait_result == WAIT_FAILED)
914 THROWF(system_error, 0,
915 "WaitForMultipleObjects failed, so we cannot wait on the condition");
917 /* we have a signal lock the condition */
918 EnterCriticalSection(&cond->waiters_count_lock);
919 cond->waiters_count--;
921 /* it's the last waiter or it's a broadcast ? */
922 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
923 && (cond->waiters_count == 0));
925 LeaveCriticalSection(&cond->waiters_count_lock);
927 /* yes it's the last waiter or it's a broadcast
928 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
932 if (!ResetEvent(cond->events[BROADCAST]))
933 THROWF(system_error, 0, "ResetEvent failed");
935 /* relock the mutex associated with the condition in accordance with the posix thread specification */
936 EnterCriticalSection(&mutex->lock);
939 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
943 unsigned long wait_result = WAIT_TIMEOUT;
945 unsigned long end = (unsigned long) (delay * 1000);
949 xbt_os_cond_wait(cond, mutex);
951 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
952 &(mutex->lock), end);
954 /* lock the threads counter and increment it */
955 EnterCriticalSection(&cond->waiters_count_lock);
956 cond->waiters_count++;
957 LeaveCriticalSection(&cond->waiters_count_lock);
959 /* unlock the mutex associate with the condition */
960 LeaveCriticalSection(&mutex->lock);
961 /* wait for a signal (broadcast or no) */
963 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
965 switch (wait_result) {
967 THROWF(timeout_error, GetLastError(),
968 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
971 THROWF(system_error, GetLastError(),
972 "WaitForMultipleObjects failed, so we cannot wait on the condition");
975 /* we have a signal lock the condition */
976 EnterCriticalSection(&cond->waiters_count_lock);
977 cond->waiters_count--;
979 /* it's the last waiter or it's a broadcast ? */
980 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
981 && (cond->waiters_count == 0));
983 LeaveCriticalSection(&cond->waiters_count_lock);
985 /* yes it's the last waiter or it's a broadcast
986 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
990 if (!ResetEvent(cond->events[BROADCAST]))
991 THROWF(system_error, 0, "ResetEvent failed");
993 /* relock the mutex associated with the condition in accordance with the posix thread specification */
994 EnterCriticalSection(&mutex->lock);
996 /*THROW_UNIMPLEMENTED; */
999 void xbt_os_cond_signal(xbt_os_cond_t cond)
1003 EnterCriticalSection(&cond->waiters_count_lock);
1004 have_waiters = cond->waiters_count > 0;
1005 LeaveCriticalSection(&cond->waiters_count_lock);
1008 if (!SetEvent(cond->events[SIGNAL]))
1009 THROWF(system_error, 0, "SetEvent failed");
1011 xbt_os_thread_yield();
1014 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1018 EnterCriticalSection(&cond->waiters_count_lock);
1019 have_waiters = cond->waiters_count > 0;
1020 LeaveCriticalSection(&cond->waiters_count_lock);
1023 SetEvent(cond->events[BROADCAST]);
1026 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1033 if (!CloseHandle(cond->events[SIGNAL]))
1036 if (!CloseHandle(cond->events[BROADCAST]))
1039 DeleteCriticalSection(&cond->waiters_count_lock);
1044 THROWF(system_error, 0, "Error while destroying the condition");
1047 typedef struct xbt_os_sem_ {
1050 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1054 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1057 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1061 if (value > INT_MAX)
1062 THROWF(arg_error, value,
1063 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1066 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1068 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1069 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1070 strerror(GetLastError()));
1076 InitializeCriticalSection(&(res->value_lock));
1081 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1084 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1087 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1088 THROWF(system_error, GetLastError(),
1089 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1090 EnterCriticalSection(&(sem->value_lock));
1092 LeaveCriticalSection(&(sem->value_lock));
1095 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1099 double end = timeout + xbt_os_time();
1102 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1105 xbt_os_sem_acquire(sem);
1106 } else { /* timeout can be zero <-> try acquire ) */
1109 seconds = (long) floor(end);
1110 milliseconds = (long) ((end - seconds) * 1000);
1111 milliseconds += (seconds * 1000);
1113 switch (WaitForSingleObject(sem->h, milliseconds)) {
1115 EnterCriticalSection(&(sem->value_lock));
1117 LeaveCriticalSection(&(sem->value_lock));
1121 THROWF(timeout_error, GetLastError(),
1122 "semaphore %p wasn't signaled before timeout (%f)", sem,
1127 THROWF(system_error, GetLastError(),
1128 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1129 strerror(GetLastError()));
1134 void xbt_os_sem_release(xbt_os_sem_t sem)
1137 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1139 if (!ReleaseSemaphore(sem->h, 1, NULL))
1140 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1141 strerror(GetLastError()));
1142 EnterCriticalSection(&(sem->value_lock));
1144 LeaveCriticalSection(&(sem->value_lock));
1147 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1150 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1152 if (!CloseHandle(sem->h))
1153 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1154 strerror(GetLastError()));
1156 DeleteCriticalSection(&(sem->value_lock));
1162 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1165 THROWF(arg_error, EINVAL,
1166 "Cannot get the value of the NULL semaphore");
1168 EnterCriticalSection(&(sem->value_lock));
1169 *svalue = sem->value;
1170 LeaveCriticalSection(&(sem->value_lock));
1176 void xbt_os_thread_set_extra_data(void *data)
1178 xbt_os_thread_self()->extra_data = data;
1181 void *xbt_os_thread_get_extra_data(void)
1183 return xbt_os_thread_self()->extra_data;