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 ************************************ */
26 #include <semaphore.h>
28 #ifdef HAVE_MUTEX_TIMEDLOCK
29 /* redefine the function header since we fail to get this from system headers on amd (at least) */
30 int pthread_mutex_timedlock(pthread_mutex_t * mutex,
31 const struct timespec *abs_timeout);
35 /* use named sempahore when sem_init() does not work */
37 static int next_sem_ID = 0;
38 static xbt_os_mutex_t next_sem_ID_lock;
41 typedef struct xbt_os_thread_ {
46 pvoid_f_pvoid_t start_routine;
47 xbt_running_ctx_t *running_ctx;
50 static xbt_os_thread_t main_thread = NULL;
52 /* thread-specific data containing the xbt_os_thread_t structure */
53 static pthread_key_t xbt_self_thread_key;
54 static int thread_mod_inited = 0;
56 /* frees the xbt_os_thread_t corresponding to the current thread */
57 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
59 if (thread == main_thread) /* just killed main thread */
62 free(thread->running_ctx);
67 /* callback: context fetching */
68 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
70 return xbt_os_thread_self()->running_ctx;
73 /* callback: termination */
74 static void _os_thread_ex_terminate(xbt_ex_t * e)
78 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
81 void xbt_os_thread_mod_preinit(void)
85 if (thread_mod_inited)
88 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
89 THROWF(system_error, errcode,
90 "pthread_key_create failed for xbt_self_thread_key");
92 main_thread = xbt_new(s_xbt_os_thread_t, 1);
93 main_thread->name = (char *) "main";
94 main_thread->start_routine = NULL;
95 main_thread->param = NULL;
96 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
97 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
99 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
100 THROWF(system_error, errcode,
101 "pthread_setspecific failed for xbt_self_thread_key");
104 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
105 __xbt_ex_terminate = _os_thread_ex_terminate;
107 thread_mod_inited = 1;
109 #ifndef HAVE_SEM_INIT
110 next_sem_ID_lock = xbt_os_mutex_init();
115 void xbt_os_thread_mod_postexit(void)
117 /* FIXME: don't try to free our key on shutdown.
118 Valgrind detects no leak if we don't, and whine if we try to */
121 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
122 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
123 free(main_thread->running_ctx);
126 thread_mod_inited = 0;
127 #ifndef HAVE_SEM_INIT
128 xbt_os_mutex_destroy(next_sem_ID_lock);
131 /* Restore the default exception setup */
132 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
133 __xbt_ex_terminate = &__xbt_ex_terminate_default;
136 int xbt_os_thread_atfork(void (*prepare)(void),
137 void (*parent)(void), void (*child)(void))
140 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
142 return pthread_atfork(prepare, parent, child);
146 static void *wrapper_start_routine(void *s)
148 xbt_os_thread_t t = s;
151 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
152 THROWF(system_error, errcode,
153 "pthread_setspecific failed for xbt_self_thread_key");
155 void *res = t->start_routine(t->param);
157 xbt_os_thread_free_thread_data(t);
161 xbt_os_thread_t xbt_os_thread_create(const char *name,
162 pvoid_f_pvoid_t start_routine,
168 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
169 res_thread->detached = 0;
170 res_thread->name = xbt_strdup(name);
171 res_thread->start_routine = start_routine;
172 res_thread->param = param;
173 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
174 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
175 res_thread->extra_data = extra_data;
177 if ((errcode = pthread_create(&(res_thread->t), NULL,
178 wrapper_start_routine, res_thread)))
179 THROWF(system_error, errcode,
180 "pthread_create failed: %s", strerror(errcode));
185 const char *xbt_os_thread_name(xbt_os_thread_t t)
190 const char *xbt_os_thread_self_name(void)
192 xbt_os_thread_t me = xbt_os_thread_self();
193 return me ? me->name : "main";
196 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
201 if ((errcode = pthread_join(thread->t, thread_return)))
202 THROWF(system_error, errcode, "pthread_join failed: %s",
204 xbt_os_thread_free_thread_data(thread);
207 void xbt_os_thread_exit(int *retval)
209 pthread_exit(retval);
212 xbt_os_thread_t xbt_os_thread_self(void)
216 if (!thread_mod_inited)
219 res = pthread_getspecific(xbt_self_thread_key);
224 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
227 if ((errcode = pthread_key_create(key, NULL)))
228 THROWF(system_error, errcode, "pthread_key_create failed");
231 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
234 if ((errcode = pthread_setspecific(key, value)))
235 THROWF(system_error, errcode, "pthread_setspecific failed");
238 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
239 return pthread_getspecific(key);
242 void xbt_os_thread_detach(xbt_os_thread_t thread)
244 thread->detached = 1;
245 pthread_detach(thread->t);
249 void xbt_os_thread_yield(void)
254 void xbt_os_thread_cancel(xbt_os_thread_t t)
256 pthread_cancel(t->t);
259 /****** mutex related functions ******/
260 typedef struct xbt_os_mutex_ {
261 /* KEEP IT IN SYNC WITH xbt_thread.c */
268 xbt_os_mutex_t xbt_os_mutex_init(void)
270 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
273 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
274 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
280 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
284 if ((errcode = pthread_mutex_lock(&(mutex->m))))
285 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
286 mutex, strerror(errcode));
290 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
295 xbt_os_mutex_acquire(mutex);
297 } else if (delay == 0) {
298 errcode = pthread_mutex_trylock(&(mutex->m));
304 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
306 THROWF(system_error, errcode,
307 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
314 #ifdef HAVE_MUTEX_TIMEDLOCK
315 struct timespec ts_end;
316 double end = delay + xbt_os_time();
318 ts_end.tv_sec = (time_t) floor(end);
319 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
320 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
322 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
324 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
325 double start = xbt_os_time();
327 errcode = pthread_mutex_trylock(&(mutex->m));
328 if (errcode == EBUSY)
329 xbt_os_thread_yield();
330 } while (errcode == EBUSY && xbt_os_time() - start < delay);
332 if (errcode == EBUSY)
335 #endif /* HAVE_MUTEX_TIMEDLOCK */
342 THROWF(timeout_error, delay,
343 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
346 THROWF(system_error, errcode,
347 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
353 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
357 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
358 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
359 mutex, strerror(errcode));
362 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
369 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
370 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
371 mutex, strerror(errcode));
375 /***** condition related functions *****/
376 typedef struct xbt_os_cond_ {
377 /* KEEP IT IN SYNC WITH xbt_thread.c */
381 xbt_os_cond_t xbt_os_cond_init(void)
383 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
385 if ((errcode = pthread_cond_init(&(res->c), NULL)))
386 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
392 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
395 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
396 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
397 cond, mutex, strerror(errcode));
401 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
405 struct timespec ts_end;
406 double end = delay + xbt_os_time();
409 xbt_os_cond_wait(cond, mutex);
411 ts_end.tv_sec = (time_t) floor(end);
412 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
413 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
416 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
420 THROWF(timeout_error, errcode,
421 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
424 THROWF(system_error, errcode,
425 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
426 delay, strerror(errcode));
431 void xbt_os_cond_signal(xbt_os_cond_t cond)
434 if ((errcode = pthread_cond_signal(&(cond->c))))
435 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
436 cond, strerror(errcode));
439 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
442 if ((errcode = pthread_cond_broadcast(&(cond->c))))
443 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
444 cond, strerror(errcode));
447 void xbt_os_cond_destroy(xbt_os_cond_t cond)
454 if ((errcode = pthread_cond_destroy(&(cond->c))))
455 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
456 cond, strerror(errcode));
460 void *xbt_os_thread_getparam(void)
462 xbt_os_thread_t t = xbt_os_thread_self();
463 return t ? t->param : NULL;
466 typedef struct xbt_os_sem_ {
467 #ifndef HAVE_SEM_INIT
475 #define SEM_FAILED (-1)
478 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
480 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
482 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
483 * Any attempt to use it leads to ENOSYS (function not implemented).
484 * If such a prehistoric system is detected, do the job with sem_open instead
487 if (sem_init(&(res->s), 0, value) != 0)
488 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
491 #else /* damn, no sem_init(). Reimplement it */
493 xbt_os_mutex_acquire(next_sem_ID_lock);
494 res->name = bprintf("/%d", ++next_sem_ID);
495 xbt_os_mutex_release(next_sem_ID_lock);
497 res->ps = sem_open(res->name, O_CREAT, 0644, value);
498 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
499 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
500 res->name[13] = '\0';
501 res->ps = sem_open(res->name, O_CREAT, 0644, value);
503 if ((res->ps == (sem_t *) SEM_FAILED))
504 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
506 /* Remove the name from the semaphore namespace: we never join on it */
507 if (sem_unlink(res->name) < 0)
508 THROWF(system_error, errno, "sem_unlink() failed: %s",
516 void xbt_os_sem_acquire(xbt_os_sem_t sem)
519 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
520 if (sem_wait(sem->ps) < 0)
521 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
524 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
529 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
532 xbt_os_sem_acquire(sem);
533 } else if (delay == 0) {
534 errcode = sem_trywait(sem->ps);
540 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
542 THROWF(system_error, errcode,
543 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
549 struct timespec ts_end;
550 double end = delay + xbt_os_time();
552 ts_end.tv_sec = (time_t) floor(end);
553 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
554 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
555 errcode = sem_timedwait(sem->s, &ts_end);
557 #else /* Okay, reimplement this function then */
558 double start = xbt_os_time();
560 errcode = sem_trywait(sem->ps);
561 if (errcode == EBUSY)
562 xbt_os_thread_yield();
563 } while (errcode == EBUSY && xbt_os_time() - start < delay);
565 if (errcode == EBUSY)
574 THROWF(timeout_error, delay,
575 "semaphore %p wasn't signaled before timeout (%f)", sem,
579 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
580 delay, strerror(errcode));
585 void xbt_os_sem_release(xbt_os_sem_t sem)
588 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
590 if (sem_post(sem->ps) < 0)
591 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
594 void xbt_os_sem_destroy(xbt_os_sem_t sem)
597 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
600 if (sem_destroy(sem->ps) < 0)
601 THROWF(system_error, errno, "sem_destroy() failed: %s",
604 if (sem_close(sem->ps) < 0)
605 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
612 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
615 THROWF(arg_error, EINVAL,
616 "Cannot get the value of the NULL semaphore");
618 if (sem_getvalue(&(sem->s), svalue) < 0)
619 THROWF(system_error, errno, "sem_getvalue() failed: %s",
623 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
625 #elif defined(_XBT_WIN32)
629 typedef struct xbt_os_thread_ {
631 HANDLE handle; /* the win thread handle */
632 unsigned long id; /* the win thread id */
633 pvoid_f_pvoid_t start_routine;
638 /* so we can specify the size of the stack of the threads */
639 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
640 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
643 /* the default size of the stack of the threads (in bytes)*/
644 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
646 /* key to the TLS containing the xbt_os_thread_t structure */
647 static unsigned long xbt_self_thread_key;
649 void xbt_os_thread_mod_preinit(void)
651 xbt_self_thread_key = TlsAlloc();
654 void xbt_os_thread_mod_postexit(void)
657 if (!TlsFree(xbt_self_thread_key))
658 THROWF(system_error, (int) GetLastError(),
659 "TlsFree() failed to cleanup the thread submodule");
662 int xbt_os_thread_atfork(void (*prepare)(void),
663 void (*parent)(void), void (*child)(void))
668 static DWORD WINAPI wrapper_start_routine(void *s)
670 xbt_os_thread_t t = (xbt_os_thread_t) s;
673 if (!TlsSetValue(xbt_self_thread_key, t))
674 THROWF(system_error, (int) GetLastError(),
675 "TlsSetValue of data describing the created thread failed");
677 rv = (DWORD *) ((t->start_routine) (t->param));
684 xbt_os_thread_t xbt_os_thread_create(const char *name,
685 pvoid_f_pvoid_t start_routine,
690 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
692 t->name = xbt_strdup(name);
693 t->start_routine = start_routine;
695 t->extra_data = extra_data;
696 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
697 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
698 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
702 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
708 const char *xbt_os_thread_name(xbt_os_thread_t t)
713 const char *xbt_os_thread_self_name(void)
715 xbt_os_thread_t t = xbt_os_thread_self();
716 return t ? t->name : "main";
719 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
722 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
723 THROWF(system_error, (int) GetLastError(),
724 "WaitForSingleObject failed");
728 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
729 THROWF(system_error, (int) GetLastError(),
730 "GetExitCodeThread failed");
733 CloseHandle(thread->handle);
740 void xbt_os_thread_exit(int *retval)
748 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
753 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
755 if (!TlsSetValue(key, value))
756 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
759 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
760 return TlsGetValue(key);
763 void xbt_os_thread_detach(xbt_os_thread_t thread)
769 xbt_os_thread_t xbt_os_thread_self(void)
771 return TlsGetValue(xbt_self_thread_key);
774 void *xbt_os_thread_getparam(void)
776 xbt_os_thread_t t = xbt_os_thread_self();
781 void xbt_os_thread_yield(void)
786 void xbt_os_thread_cancel(xbt_os_thread_t t)
788 if (!TerminateThread(t->handle, 0))
789 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
792 /****** mutex related functions ******/
793 typedef struct xbt_os_mutex_ {
794 /* KEEP IT IN SYNC WITH xbt_thread.c */
795 CRITICAL_SECTION lock;
798 xbt_os_mutex_t xbt_os_mutex_init(void)
800 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
802 /* initialize the critical section object */
803 InitializeCriticalSection(&(res->lock));
808 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
810 EnterCriticalSection(&mutex->lock);
813 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
818 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
821 LeaveCriticalSection(&mutex->lock);
825 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
831 DeleteCriticalSection(&mutex->lock);
835 /***** condition related functions *****/
836 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
842 typedef struct xbt_os_cond_ {
843 /* KEEP IT IN SYNC WITH xbt_thread.c */
844 HANDLE events[MAX_EVENTS];
846 unsigned int waiters_count; /* the number of waiters */
847 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
850 xbt_os_cond_t xbt_os_cond_init(void)
853 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
855 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
857 /* initialize the critical section object */
858 InitializeCriticalSection(&res->waiters_count_lock);
860 res->waiters_count = 0;
862 /* Create an auto-reset event */
863 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
865 if (!res->events[SIGNAL]) {
866 DeleteCriticalSection(&res->waiters_count_lock);
868 THROWF(system_error, 0, "CreateEvent failed for the signals");
871 /* Create a manual-reset event. */
872 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
874 if (!res->events[BROADCAST]) {
876 DeleteCriticalSection(&res->waiters_count_lock);
877 CloseHandle(res->events[SIGNAL]);
879 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
885 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
888 unsigned long wait_result;
891 /* lock the threads counter and increment it */
892 EnterCriticalSection(&cond->waiters_count_lock);
893 cond->waiters_count++;
894 LeaveCriticalSection(&cond->waiters_count_lock);
896 /* unlock the mutex associate with the condition */
897 LeaveCriticalSection(&mutex->lock);
899 /* wait for a signal (broadcast or no) */
900 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
902 if (wait_result == WAIT_FAILED)
903 THROWF(system_error, 0,
904 "WaitForMultipleObjects failed, so we cannot wait on the condition");
906 /* we have a signal lock the condition */
907 EnterCriticalSection(&cond->waiters_count_lock);
908 cond->waiters_count--;
910 /* it's the last waiter or it's a broadcast ? */
911 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
912 && (cond->waiters_count == 0));
914 LeaveCriticalSection(&cond->waiters_count_lock);
916 /* yes it's the last waiter or it's a broadcast
917 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
921 if (!ResetEvent(cond->events[BROADCAST]))
922 THROWF(system_error, 0, "ResetEvent failed");
924 /* relock the mutex associated with the condition in accordance with the posix thread specification */
925 EnterCriticalSection(&mutex->lock);
928 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
932 unsigned long wait_result = WAIT_TIMEOUT;
934 unsigned long end = (unsigned long) (delay * 1000);
938 xbt_os_cond_wait(cond, mutex);
940 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
941 &(mutex->lock), end);
943 /* lock the threads counter and increment it */
944 EnterCriticalSection(&cond->waiters_count_lock);
945 cond->waiters_count++;
946 LeaveCriticalSection(&cond->waiters_count_lock);
948 /* unlock the mutex associate with the condition */
949 LeaveCriticalSection(&mutex->lock);
950 /* wait for a signal (broadcast or no) */
952 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
954 switch (wait_result) {
956 THROWF(timeout_error, GetLastError(),
957 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
960 THROWF(system_error, GetLastError(),
961 "WaitForMultipleObjects failed, so we cannot wait on the condition");
964 /* we have a signal lock the condition */
965 EnterCriticalSection(&cond->waiters_count_lock);
966 cond->waiters_count--;
968 /* it's the last waiter or it's a broadcast ? */
969 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
970 && (cond->waiters_count == 0));
972 LeaveCriticalSection(&cond->waiters_count_lock);
974 /* yes it's the last waiter or it's a broadcast
975 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
979 if (!ResetEvent(cond->events[BROADCAST]))
980 THROWF(system_error, 0, "ResetEvent failed");
982 /* relock the mutex associated with the condition in accordance with the posix thread specification */
983 EnterCriticalSection(&mutex->lock);
985 /*THROW_UNIMPLEMENTED; */
988 void xbt_os_cond_signal(xbt_os_cond_t cond)
992 EnterCriticalSection(&cond->waiters_count_lock);
993 have_waiters = cond->waiters_count > 0;
994 LeaveCriticalSection(&cond->waiters_count_lock);
997 if (!SetEvent(cond->events[SIGNAL]))
998 THROWF(system_error, 0, "SetEvent failed");
1000 xbt_os_thread_yield();
1003 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1007 EnterCriticalSection(&cond->waiters_count_lock);
1008 have_waiters = cond->waiters_count > 0;
1009 LeaveCriticalSection(&cond->waiters_count_lock);
1012 SetEvent(cond->events[BROADCAST]);
1015 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1022 if (!CloseHandle(cond->events[SIGNAL]))
1025 if (!CloseHandle(cond->events[BROADCAST]))
1028 DeleteCriticalSection(&cond->waiters_count_lock);
1033 THROWF(system_error, 0, "Error while destroying the condition");
1036 typedef struct xbt_os_sem_ {
1039 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1043 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1046 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1050 if (value > INT_MAX)
1051 THROWF(arg_error, value,
1052 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1055 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1057 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1058 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1059 strerror(GetLastError()));
1065 InitializeCriticalSection(&(res->value_lock));
1070 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1073 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1076 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1077 THROWF(system_error, GetLastError(),
1078 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1079 EnterCriticalSection(&(sem->value_lock));
1081 LeaveCriticalSection(&(sem->value_lock));
1084 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1088 double end = timeout + xbt_os_time();
1091 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1094 xbt_os_sem_acquire(sem);
1095 } else { /* timeout can be zero <-> try acquire ) */
1098 seconds = (long) floor(end);
1099 milliseconds = (long) ((end - seconds) * 1000);
1100 milliseconds += (seconds * 1000);
1102 switch (WaitForSingleObject(sem->h, milliseconds)) {
1104 EnterCriticalSection(&(sem->value_lock));
1106 LeaveCriticalSection(&(sem->value_lock));
1110 THROWF(timeout_error, GetLastError(),
1111 "semaphore %p wasn't signaled before timeout (%f)", sem,
1116 THROWF(system_error, GetLastError(),
1117 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1118 strerror(GetLastError()));
1123 void xbt_os_sem_release(xbt_os_sem_t sem)
1126 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1128 if (!ReleaseSemaphore(sem->h, 1, NULL))
1129 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1130 strerror(GetLastError()));
1131 EnterCriticalSection(&(sem->value_lock));
1133 LeaveCriticalSection(&(sem->value_lock));
1136 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1139 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1141 if (!CloseHandle(sem->h))
1142 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1143 strerror(GetLastError()));
1145 DeleteCriticalSection(&(sem->value_lock));
1151 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1154 THROWF(arg_error, EINVAL,
1155 "Cannot get the value of the NULL semaphore");
1157 EnterCriticalSection(&(sem->value_lock));
1158 *svalue = sem->value;
1159 LeaveCriticalSection(&(sem->value_lock));
1166 /** @brief Returns the amount of cores on the current host */
1167 int xbt_os_get_numcores(void) {
1169 SYSTEM_INFO sysinfo;
1170 GetSystemInfo(&sysinfo);
1171 return sysinfo.dwNumberOfProcessors;
1177 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1178 sysctl(nm, 2, &count, &len, NULL, 0);
1182 sysctl(nm, 2, &count, &len, NULL, 0);
1183 if(count < 1) { count = 1; }
1187 return sysconf(_SC_NPROCESSORS_ONLN);
1192 /***** reentrant mutexes *****/
1193 typedef struct xbt_os_rmutex_ {
1194 xbt_os_mutex_t mutex;
1195 xbt_os_thread_t owner;
1197 } s_xbt_os_rmutex_t;
1199 void xbt_os_thread_set_extra_data(void *data)
1201 xbt_os_thread_self()->extra_data = data;
1204 void *xbt_os_thread_get_extra_data(void)
1206 return xbt_os_thread_self()->extra_data;
1209 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1211 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1212 rmutex->mutex = xbt_os_mutex_init();
1213 rmutex->owner = NULL;
1218 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1220 xbt_os_thread_t self = xbt_os_thread_self();
1223 /* the thread module is not initialized yet */
1224 rmutex->owner = NULL;
1228 if (self != rmutex->owner) {
1229 xbt_os_mutex_acquire(rmutex->mutex);
1230 rmutex->owner = self;
1237 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1239 if (rmutex->owner == NULL) {
1240 /* the thread module was not initialized */
1244 xbt_assert(rmutex->owner == xbt_os_thread_self());
1246 if (--rmutex->count == 0) {
1247 rmutex->owner = NULL;
1248 xbt_os_mutex_release(rmutex->mutex);
1252 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1254 xbt_os_mutex_destroy(rmutex->mutex);