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 /***** condition related functions *****/
362 typedef struct xbt_os_cond_ {
363 /* KEEP IT IN SYNC WITH xbt_thread.c */
367 xbt_os_cond_t xbt_os_cond_init(void)
369 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
371 if ((errcode = pthread_cond_init(&(res->c), NULL)))
372 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
378 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
381 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
382 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
383 cond, mutex, strerror(errcode));
387 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
391 struct timespec ts_end;
392 double end = delay + xbt_os_time();
395 xbt_os_cond_wait(cond, mutex);
397 ts_end.tv_sec = (time_t) floor(end);
398 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
399 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
402 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
406 THROWF(timeout_error, errcode,
407 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
410 THROWF(system_error, errcode,
411 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
412 delay, strerror(errcode));
417 void xbt_os_cond_signal(xbt_os_cond_t cond)
420 if ((errcode = pthread_cond_signal(&(cond->c))))
421 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
422 cond, strerror(errcode));
425 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
428 if ((errcode = pthread_cond_broadcast(&(cond->c))))
429 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
430 cond, strerror(errcode));
433 void xbt_os_cond_destroy(xbt_os_cond_t cond)
440 if ((errcode = pthread_cond_destroy(&(cond->c))))
441 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
442 cond, strerror(errcode));
446 void *xbt_os_thread_getparam(void)
448 xbt_os_thread_t t = xbt_os_thread_self();
449 return t ? t->param : NULL;
452 typedef struct xbt_os_sem_ {
453 #ifndef HAVE_SEM_INIT
461 #define SEM_FAILED (-1)
464 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
466 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
468 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
469 * Any attempt to use it leads to ENOSYS (function not implemented).
470 * If such a prehistoric system is detected, do the job with sem_open instead
473 if (sem_init(&(res->s), 0, value) != 0)
474 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
477 #else /* damn, no sem_init(). Reimplement it */
479 xbt_os_mutex_acquire(next_sem_ID_lock);
480 res->name = bprintf("/%d", ++next_sem_ID);
481 xbt_os_mutex_release(next_sem_ID_lock);
483 res->ps = sem_open(res->name, O_CREAT, 0644, value);
484 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
485 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
486 res->name[13] = '\0';
487 res->ps = sem_open(res->name, O_CREAT, 0644, 1);
489 if ((res->ps == (sem_t *) SEM_FAILED))
490 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
492 /* Remove the name from the semaphore namespace: we never join on it */
493 if (sem_unlink(res->name) < 0)
494 THROWF(system_error, errno, "sem_unlink() failed: %s",
502 void xbt_os_sem_acquire(xbt_os_sem_t sem)
505 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
506 if (sem_wait(sem->ps) < 0)
507 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
510 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
515 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
518 xbt_os_sem_acquire(sem);
519 } else if (delay == 0) {
520 errcode = sem_trywait(sem->ps);
526 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
528 THROWF(system_error, errcode,
529 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
535 struct timespec ts_end;
536 double end = delay + xbt_os_time();
538 ts_end.tv_sec = (time_t) floor(end);
539 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
540 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
541 errcode = sem_timedwait(sem->s, &ts_end);
543 #else /* Okay, reimplement this function then */
544 double start = xbt_os_time();
546 errcode = sem_trywait(sem->ps);
547 if (errcode == EBUSY)
548 xbt_os_thread_yield();
549 } while (errcode == EBUSY && xbt_os_time() - start < delay);
551 if (errcode == EBUSY)
560 THROWF(timeout_error, delay,
561 "semaphore %p wasn't signaled before timeout (%f)", sem,
565 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
566 delay, strerror(errcode));
571 void xbt_os_sem_release(xbt_os_sem_t sem)
574 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
576 if (sem_post(sem->ps) < 0)
577 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
580 void xbt_os_sem_destroy(xbt_os_sem_t sem)
583 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
586 if (sem_destroy(sem->ps) < 0)
587 THROWF(system_error, errno, "sem_destroy() failed: %s",
590 if (sem_close(sem->ps) < 0)
591 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
598 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
601 THROWF(arg_error, EINVAL,
602 "Cannot get the value of the NULL semaphore");
604 if (sem_getvalue(&(sem->s), svalue) < 0)
605 THROWF(system_error, errno, "sem_getvalue() failed: %s",
609 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
611 #elif defined(_XBT_WIN32)
615 typedef struct xbt_os_thread_ {
617 HANDLE handle; /* the win thread handle */
618 unsigned long id; /* the win thread id */
619 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 THROWF(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 THROWF(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,
676 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
678 t->name = xbt_strdup(name);
679 t->start_routine = start_routine;
681 t->extra_data = extra_data;
682 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
683 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
684 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
688 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
694 const char *xbt_os_thread_name(xbt_os_thread_t t)
699 const char *xbt_os_thread_self_name(void)
701 xbt_os_thread_t t = xbt_os_thread_self();
702 return t ? t->name : "main";
705 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
708 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
709 THROWF(system_error, (int) GetLastError(),
710 "WaitForSingleObject failed");
714 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
715 THROWF(system_error, (int) GetLastError(),
716 "GetExitCodeThread failed");
719 CloseHandle(thread->handle);
727 void xbt_os_thread_exit(int *retval)
735 void xbt_os_thread_detach(xbt_os_thread_t thread)
741 xbt_os_thread_t xbt_os_thread_self(void)
743 return TlsGetValue(xbt_self_thread_key);
746 void *xbt_os_thread_getparam(void)
748 xbt_os_thread_t t = xbt_os_thread_self();
753 void xbt_os_thread_yield(void)
758 void xbt_os_thread_cancel(xbt_os_thread_t t)
760 if (!TerminateThread(t->handle, 0))
761 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
764 /****** mutex related functions ******/
765 typedef struct xbt_os_mutex_ {
766 /* KEEP IT IN SYNC WITH xbt_thread.c */
767 CRITICAL_SECTION lock;
770 xbt_os_mutex_t xbt_os_mutex_init(void)
772 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
774 /* initialize the critical section object */
775 InitializeCriticalSection(&(res->lock));
780 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
782 EnterCriticalSection(&mutex->lock);
785 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
790 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
793 LeaveCriticalSection(&mutex->lock);
797 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
803 DeleteCriticalSection(&mutex->lock);
807 /***** condition related functions *****/
808 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
814 typedef struct xbt_os_cond_ {
815 /* KEEP IT IN SYNC WITH xbt_thread.c */
816 HANDLE events[MAX_EVENTS];
818 unsigned int waiters_count; /* the number of waiters */
819 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
822 xbt_os_cond_t xbt_os_cond_init(void)
825 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
827 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
829 /* initialize the critical section object */
830 InitializeCriticalSection(&res->waiters_count_lock);
832 res->waiters_count = 0;
834 /* Create an auto-reset event */
835 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
837 if (!res->events[SIGNAL]) {
838 DeleteCriticalSection(&res->waiters_count_lock);
840 THROWF(system_error, 0, "CreateEvent failed for the signals");
843 /* Create a manual-reset event. */
844 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
846 if (!res->events[BROADCAST]) {
848 DeleteCriticalSection(&res->waiters_count_lock);
849 CloseHandle(res->events[SIGNAL]);
851 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
857 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
860 unsigned long wait_result;
863 /* lock the threads counter and increment it */
864 EnterCriticalSection(&cond->waiters_count_lock);
865 cond->waiters_count++;
866 LeaveCriticalSection(&cond->waiters_count_lock);
868 /* unlock the mutex associate with the condition */
869 LeaveCriticalSection(&mutex->lock);
871 /* wait for a signal (broadcast or no) */
872 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
874 if (wait_result == WAIT_FAILED)
875 THROWF(system_error, 0,
876 "WaitForMultipleObjects failed, so we cannot wait on the condition");
878 /* we have a signal lock the condition */
879 EnterCriticalSection(&cond->waiters_count_lock);
880 cond->waiters_count--;
882 /* it's the last waiter or it's a broadcast ? */
883 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
884 && (cond->waiters_count == 0));
886 LeaveCriticalSection(&cond->waiters_count_lock);
888 /* yes it's the last waiter or it's a broadcast
889 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
893 if (!ResetEvent(cond->events[BROADCAST]))
894 THROWF(system_error, 0, "ResetEvent failed");
896 /* relock the mutex associated with the condition in accordance with the posix thread specification */
897 EnterCriticalSection(&mutex->lock);
900 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
904 unsigned long wait_result = WAIT_TIMEOUT;
906 unsigned long end = (unsigned long) (delay * 1000);
910 xbt_os_cond_wait(cond, mutex);
912 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
913 &(mutex->lock), end);
915 /* lock the threads counter and increment it */
916 EnterCriticalSection(&cond->waiters_count_lock);
917 cond->waiters_count++;
918 LeaveCriticalSection(&cond->waiters_count_lock);
920 /* unlock the mutex associate with the condition */
921 LeaveCriticalSection(&mutex->lock);
922 /* wait for a signal (broadcast or no) */
924 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
926 switch (wait_result) {
928 THROWF(timeout_error, GetLastError(),
929 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
932 THROWF(system_error, GetLastError(),
933 "WaitForMultipleObjects failed, so we cannot wait on the condition");
936 /* we have a signal lock the condition */
937 EnterCriticalSection(&cond->waiters_count_lock);
938 cond->waiters_count--;
940 /* it's the last waiter or it's a broadcast ? */
941 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
942 && (cond->waiters_count == 0));
944 LeaveCriticalSection(&cond->waiters_count_lock);
946 /* yes it's the last waiter or it's a broadcast
947 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
951 if (!ResetEvent(cond->events[BROADCAST]))
952 THROWF(system_error, 0, "ResetEvent failed");
954 /* relock the mutex associated with the condition in accordance with the posix thread specification */
955 EnterCriticalSection(&mutex->lock);
957 /*THROW_UNIMPLEMENTED; */
960 void xbt_os_cond_signal(xbt_os_cond_t cond)
964 EnterCriticalSection(&cond->waiters_count_lock);
965 have_waiters = cond->waiters_count > 0;
966 LeaveCriticalSection(&cond->waiters_count_lock);
969 if (!SetEvent(cond->events[SIGNAL]))
970 THROWF(system_error, 0, "SetEvent failed");
972 xbt_os_thread_yield();
975 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
979 EnterCriticalSection(&cond->waiters_count_lock);
980 have_waiters = cond->waiters_count > 0;
981 LeaveCriticalSection(&cond->waiters_count_lock);
984 SetEvent(cond->events[BROADCAST]);
987 void xbt_os_cond_destroy(xbt_os_cond_t cond)
994 if (!CloseHandle(cond->events[SIGNAL]))
997 if (!CloseHandle(cond->events[BROADCAST]))
1000 DeleteCriticalSection(&cond->waiters_count_lock);
1005 THROWF(system_error, 0, "Error while destroying the condition");
1008 typedef struct xbt_os_sem_ {
1011 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1015 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1018 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1022 if (value > INT_MAX)
1023 THROWF(arg_error, value,
1024 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1027 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1029 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1030 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1031 strerror(GetLastError()));
1037 InitializeCriticalSection(&(res->value_lock));
1042 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1045 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1048 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1049 THROWF(system_error, GetLastError(),
1050 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1051 EnterCriticalSection(&(sem->value_lock));
1053 LeaveCriticalSection(&(sem->value_lock));
1056 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1060 double end = timeout + xbt_os_time();
1063 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1066 xbt_os_sem_acquire(sem);
1067 } else { /* timeout can be zero <-> try acquire ) */
1070 seconds = (long) floor(end);
1071 milliseconds = (long) ((end - seconds) * 1000);
1072 milliseconds += (seconds * 1000);
1074 switch (WaitForSingleObject(sem->h, milliseconds)) {
1076 EnterCriticalSection(&(sem->value_lock));
1078 LeaveCriticalSection(&(sem->value_lock));
1082 THROWF(timeout_error, GetLastError(),
1083 "semaphore %p wasn't signaled before timeout (%f)", sem,
1088 THROWF(system_error, GetLastError(),
1089 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1090 strerror(GetLastError()));
1095 void xbt_os_sem_release(xbt_os_sem_t sem)
1098 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1100 if (!ReleaseSemaphore(sem->h, 1, NULL))
1101 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1102 strerror(GetLastError()));
1103 EnterCriticalSection(&(sem->value_lock));
1105 LeaveCriticalSection(&(sem->value_lock));
1108 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1111 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1113 if (!CloseHandle(sem->h))
1114 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1115 strerror(GetLastError()));
1117 DeleteCriticalSection(&(sem->value_lock));
1123 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1126 THROWF(arg_error, EINVAL,
1127 "Cannot get the value of the NULL semaphore");
1129 EnterCriticalSection(&(sem->value_lock));
1130 *svalue = sem->value;
1131 LeaveCriticalSection(&(sem->value_lock));
1137 void xbt_os_thread_set_extra_data(void *data)
1139 xbt_os_thread_self()->extra_data = data;
1142 void *xbt_os_thread_get_extra_data(void)
1144 return xbt_os_thread_self()->extra_data;
1147 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1149 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 0);
1150 rmutex->mutex = xbt_os_mutex_init();
1151 rmutex->owner = NULL;
1156 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1158 xbt_os_thread_t self = xbt_os_thread_self();
1159 xbt_assert(self != NULL, "Cannot get my own thread object (is the thread module initialized?)");
1161 if (self != rmutex->owner) {
1162 xbt_os_mutex_acquire(rmutex->mutex);
1163 rmutex->owner = self;
1170 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1172 xbt_assert(rmutex->owner == xbt_os_thread_self());
1174 if (--rmutex->count == 0) {
1175 rmutex->owner = NULL;
1176 xbt_os_mutex_release(rmutex->mutex);
1180 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1182 xbt_os_mutex_destroy(rmutex->mutex);