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 /* this function is critical to tesh+mmalloc, don't mess with it */
137 int xbt_os_thread_atfork(void (*prepare)(void),
138 void (*parent)(void), void (*child)(void))
141 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
143 return pthread_atfork(prepare, parent, child);
147 static void *wrapper_start_routine(void *s)
149 xbt_os_thread_t t = s;
152 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
153 THROWF(system_error, errcode,
154 "pthread_setspecific failed for xbt_self_thread_key");
156 void *res = t->start_routine(t->param);
158 xbt_os_thread_free_thread_data(t);
162 xbt_os_thread_t xbt_os_thread_create(const char *name,
163 pvoid_f_pvoid_t start_routine,
169 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
170 res_thread->detached = 0;
171 res_thread->name = xbt_strdup(name);
172 res_thread->start_routine = start_routine;
173 res_thread->param = param;
174 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
175 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
176 res_thread->extra_data = extra_data;
178 if ((errcode = pthread_create(&(res_thread->t), NULL,
179 wrapper_start_routine, res_thread)))
180 THROWF(system_error, errcode,
181 "pthread_create failed: %s", strerror(errcode));
186 const char *xbt_os_thread_name(xbt_os_thread_t t)
191 const char *xbt_os_thread_self_name(void)
193 xbt_os_thread_t me = xbt_os_thread_self();
194 return me ? me->name : "main";
197 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
202 if ((errcode = pthread_join(thread->t, thread_return)))
203 THROWF(system_error, errcode, "pthread_join failed: %s",
205 xbt_os_thread_free_thread_data(thread);
208 void xbt_os_thread_exit(int *retval)
210 pthread_exit(retval);
213 xbt_os_thread_t xbt_os_thread_self(void)
217 if (!thread_mod_inited)
220 res = pthread_getspecific(xbt_self_thread_key);
225 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
228 if ((errcode = pthread_key_create(key, NULL)))
229 THROWF(system_error, errcode, "pthread_key_create failed");
232 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
235 if ((errcode = pthread_setspecific(key, value)))
236 THROWF(system_error, errcode, "pthread_setspecific failed");
239 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
240 return pthread_getspecific(key);
243 void xbt_os_thread_detach(xbt_os_thread_t thread)
245 thread->detached = 1;
246 pthread_detach(thread->t);
250 void xbt_os_thread_yield(void)
255 void xbt_os_thread_cancel(xbt_os_thread_t t)
257 pthread_cancel(t->t);
260 /****** mutex related functions ******/
261 typedef struct xbt_os_mutex_ {
262 /* KEEP IT IN SYNC WITH xbt_thread.c */
269 xbt_os_mutex_t xbt_os_mutex_init(void)
271 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
274 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
275 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
281 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
285 if ((errcode = pthread_mutex_lock(&(mutex->m))))
286 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
287 mutex, strerror(errcode));
291 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
296 xbt_os_mutex_acquire(mutex);
298 } else if (delay == 0) {
299 errcode = pthread_mutex_trylock(&(mutex->m));
305 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
307 THROWF(system_error, errcode,
308 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
315 #ifdef HAVE_MUTEX_TIMEDLOCK
316 struct timespec ts_end;
317 double end = delay + xbt_os_time();
319 ts_end.tv_sec = (time_t) floor(end);
320 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
321 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
323 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
325 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
326 double start = xbt_os_time();
328 errcode = pthread_mutex_trylock(&(mutex->m));
329 if (errcode == EBUSY)
330 xbt_os_thread_yield();
331 } while (errcode == EBUSY && xbt_os_time() - start < delay);
333 if (errcode == EBUSY)
336 #endif /* HAVE_MUTEX_TIMEDLOCK */
343 THROWF(timeout_error, delay,
344 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
347 THROWF(system_error, errcode,
348 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
354 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
358 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
359 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
360 mutex, strerror(errcode));
363 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
370 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
371 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
372 mutex, strerror(errcode));
376 /***** condition related functions *****/
377 typedef struct xbt_os_cond_ {
378 /* KEEP IT IN SYNC WITH xbt_thread.c */
382 xbt_os_cond_t xbt_os_cond_init(void)
384 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
386 if ((errcode = pthread_cond_init(&(res->c), NULL)))
387 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
393 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
396 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
397 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
398 cond, mutex, strerror(errcode));
402 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
406 struct timespec ts_end;
407 double end = delay + xbt_os_time();
410 xbt_os_cond_wait(cond, mutex);
412 ts_end.tv_sec = (time_t) floor(end);
413 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
414 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
417 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
421 THROWF(timeout_error, errcode,
422 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
425 THROWF(system_error, errcode,
426 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
427 delay, strerror(errcode));
432 void xbt_os_cond_signal(xbt_os_cond_t cond)
435 if ((errcode = pthread_cond_signal(&(cond->c))))
436 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
437 cond, strerror(errcode));
440 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
443 if ((errcode = pthread_cond_broadcast(&(cond->c))))
444 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
445 cond, strerror(errcode));
448 void xbt_os_cond_destroy(xbt_os_cond_t cond)
455 if ((errcode = pthread_cond_destroy(&(cond->c))))
456 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
457 cond, strerror(errcode));
461 void *xbt_os_thread_getparam(void)
463 xbt_os_thread_t t = xbt_os_thread_self();
464 return t ? t->param : NULL;
467 typedef struct xbt_os_sem_ {
468 #ifndef HAVE_SEM_INIT
476 #define SEM_FAILED (-1)
479 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
481 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
483 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
484 * Any attempt to use it leads to ENOSYS (function not implemented).
485 * If such a prehistoric system is detected, do the job with sem_open instead
488 if (sem_init(&(res->s), 0, value) != 0)
489 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
492 #else /* damn, no sem_init(). Reimplement it */
494 xbt_os_mutex_acquire(next_sem_ID_lock);
495 res->name = bprintf("/%d", ++next_sem_ID);
496 xbt_os_mutex_release(next_sem_ID_lock);
498 res->ps = sem_open(res->name, O_CREAT, 0644, value);
499 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
500 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
501 res->name[13] = '\0';
502 res->ps = sem_open(res->name, O_CREAT, 0644, value);
504 if ((res->ps == (sem_t *) SEM_FAILED))
505 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
507 /* Remove the name from the semaphore namespace: we never join on it */
508 if (sem_unlink(res->name) < 0)
509 THROWF(system_error, errno, "sem_unlink() failed: %s",
517 void xbt_os_sem_acquire(xbt_os_sem_t sem)
520 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
521 if (sem_wait(sem->ps) < 0)
522 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
525 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
530 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
533 xbt_os_sem_acquire(sem);
534 } else if (delay == 0) {
535 errcode = sem_trywait(sem->ps);
541 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
543 THROWF(system_error, errcode,
544 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
550 struct timespec ts_end;
551 double end = delay + xbt_os_time();
553 ts_end.tv_sec = (time_t) floor(end);
554 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
555 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
556 errcode = sem_timedwait(sem->s, &ts_end);
558 #else /* Okay, reimplement this function then */
559 double start = xbt_os_time();
561 errcode = sem_trywait(sem->ps);
562 if (errcode == EBUSY)
563 xbt_os_thread_yield();
564 } while (errcode == EBUSY && xbt_os_time() - start < delay);
566 if (errcode == EBUSY)
575 THROWF(timeout_error, delay,
576 "semaphore %p wasn't signaled before timeout (%f)", sem,
580 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
581 delay, strerror(errcode));
586 void xbt_os_sem_release(xbt_os_sem_t sem)
589 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
591 if (sem_post(sem->ps) < 0)
592 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
595 void xbt_os_sem_destroy(xbt_os_sem_t sem)
598 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
601 if (sem_destroy(sem->ps) < 0)
602 THROWF(system_error, errno, "sem_destroy() failed: %s",
605 if (sem_close(sem->ps) < 0)
606 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
613 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
616 THROWF(arg_error, EINVAL,
617 "Cannot get the value of the NULL semaphore");
619 if (sem_getvalue(&(sem->s), svalue) < 0)
620 THROWF(system_error, errno, "sem_getvalue() failed: %s",
624 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
626 #elif defined(_XBT_WIN32)
630 typedef struct xbt_os_thread_ {
632 HANDLE handle; /* the win thread handle */
633 unsigned long id; /* the win thread id */
634 pvoid_f_pvoid_t start_routine;
639 /* so we can specify the size of the stack of the threads */
640 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
641 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
644 /* the default size of the stack of the threads (in bytes)*/
645 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
647 /* key to the TLS containing the xbt_os_thread_t structure */
648 static unsigned long xbt_self_thread_key;
650 void xbt_os_thread_mod_preinit(void)
652 xbt_self_thread_key = TlsAlloc();
655 void xbt_os_thread_mod_postexit(void)
658 if (!TlsFree(xbt_self_thread_key))
659 THROWF(system_error, (int) GetLastError(),
660 "TlsFree() failed to cleanup the thread submodule");
663 int xbt_os_thread_atfork(void (*prepare)(void),
664 void (*parent)(void), void (*child)(void))
669 static DWORD WINAPI wrapper_start_routine(void *s)
671 xbt_os_thread_t t = (xbt_os_thread_t) s;
674 if (!TlsSetValue(xbt_self_thread_key, t))
675 THROWF(system_error, (int) GetLastError(),
676 "TlsSetValue of data describing the created thread failed");
678 rv = (DWORD *) ((t->start_routine) (t->param));
685 xbt_os_thread_t xbt_os_thread_create(const char *name,
686 pvoid_f_pvoid_t start_routine,
691 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
693 t->name = xbt_strdup(name);
694 t->start_routine = start_routine;
696 t->extra_data = extra_data;
697 t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
698 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
699 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
703 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
709 const char *xbt_os_thread_name(xbt_os_thread_t t)
714 const char *xbt_os_thread_self_name(void)
716 xbt_os_thread_t t = xbt_os_thread_self();
717 return t ? t->name : "main";
720 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
723 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
724 THROWF(system_error, (int) GetLastError(),
725 "WaitForSingleObject failed");
729 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
730 THROWF(system_error, (int) GetLastError(),
731 "GetExitCodeThread failed");
734 CloseHandle(thread->handle);
741 void xbt_os_thread_exit(int *retval)
749 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
754 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
756 if (!TlsSetValue(key, value))
757 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
760 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
761 return TlsGetValue(key);
764 void xbt_os_thread_detach(xbt_os_thread_t thread)
770 xbt_os_thread_t xbt_os_thread_self(void)
772 return TlsGetValue(xbt_self_thread_key);
775 void *xbt_os_thread_getparam(void)
777 xbt_os_thread_t t = xbt_os_thread_self();
782 void xbt_os_thread_yield(void)
787 void xbt_os_thread_cancel(xbt_os_thread_t t)
789 if (!TerminateThread(t->handle, 0))
790 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
793 /****** mutex related functions ******/
794 typedef struct xbt_os_mutex_ {
795 /* KEEP IT IN SYNC WITH xbt_thread.c */
796 CRITICAL_SECTION lock;
799 xbt_os_mutex_t xbt_os_mutex_init(void)
801 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
803 /* initialize the critical section object */
804 InitializeCriticalSection(&(res->lock));
809 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
811 EnterCriticalSection(&mutex->lock);
814 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
819 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
822 LeaveCriticalSection(&mutex->lock);
826 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
832 DeleteCriticalSection(&mutex->lock);
836 /***** condition related functions *****/
837 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
843 typedef struct xbt_os_cond_ {
844 /* KEEP IT IN SYNC WITH xbt_thread.c */
845 HANDLE events[MAX_EVENTS];
847 unsigned int waiters_count; /* the number of waiters */
848 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
851 xbt_os_cond_t xbt_os_cond_init(void)
854 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
856 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
858 /* initialize the critical section object */
859 InitializeCriticalSection(&res->waiters_count_lock);
861 res->waiters_count = 0;
863 /* Create an auto-reset event */
864 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
866 if (!res->events[SIGNAL]) {
867 DeleteCriticalSection(&res->waiters_count_lock);
869 THROWF(system_error, 0, "CreateEvent failed for the signals");
872 /* Create a manual-reset event. */
873 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
875 if (!res->events[BROADCAST]) {
877 DeleteCriticalSection(&res->waiters_count_lock);
878 CloseHandle(res->events[SIGNAL]);
880 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
886 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
889 unsigned long wait_result;
892 /* lock the threads counter and increment it */
893 EnterCriticalSection(&cond->waiters_count_lock);
894 cond->waiters_count++;
895 LeaveCriticalSection(&cond->waiters_count_lock);
897 /* unlock the mutex associate with the condition */
898 LeaveCriticalSection(&mutex->lock);
900 /* wait for a signal (broadcast or no) */
901 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
903 if (wait_result == WAIT_FAILED)
904 THROWF(system_error, 0,
905 "WaitForMultipleObjects failed, so we cannot wait on the condition");
907 /* we have a signal lock the condition */
908 EnterCriticalSection(&cond->waiters_count_lock);
909 cond->waiters_count--;
911 /* it's the last waiter or it's a broadcast ? */
912 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
913 && (cond->waiters_count == 0));
915 LeaveCriticalSection(&cond->waiters_count_lock);
917 /* yes it's the last waiter or it's a broadcast
918 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
922 if (!ResetEvent(cond->events[BROADCAST]))
923 THROWF(system_error, 0, "ResetEvent failed");
925 /* relock the mutex associated with the condition in accordance with the posix thread specification */
926 EnterCriticalSection(&mutex->lock);
929 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
933 unsigned long wait_result = WAIT_TIMEOUT;
935 unsigned long end = (unsigned long) (delay * 1000);
939 xbt_os_cond_wait(cond, mutex);
941 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
942 &(mutex->lock), end);
944 /* lock the threads counter and increment it */
945 EnterCriticalSection(&cond->waiters_count_lock);
946 cond->waiters_count++;
947 LeaveCriticalSection(&cond->waiters_count_lock);
949 /* unlock the mutex associate with the condition */
950 LeaveCriticalSection(&mutex->lock);
951 /* wait for a signal (broadcast or no) */
953 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
955 switch (wait_result) {
957 THROWF(timeout_error, GetLastError(),
958 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
961 THROWF(system_error, GetLastError(),
962 "WaitForMultipleObjects failed, so we cannot wait on the condition");
965 /* we have a signal lock the condition */
966 EnterCriticalSection(&cond->waiters_count_lock);
967 cond->waiters_count--;
969 /* it's the last waiter or it's a broadcast ? */
970 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
971 && (cond->waiters_count == 0));
973 LeaveCriticalSection(&cond->waiters_count_lock);
975 /* yes it's the last waiter or it's a broadcast
976 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
980 if (!ResetEvent(cond->events[BROADCAST]))
981 THROWF(system_error, 0, "ResetEvent failed");
983 /* relock the mutex associated with the condition in accordance with the posix thread specification */
984 EnterCriticalSection(&mutex->lock);
986 /*THROW_UNIMPLEMENTED; */
989 void xbt_os_cond_signal(xbt_os_cond_t cond)
993 EnterCriticalSection(&cond->waiters_count_lock);
994 have_waiters = cond->waiters_count > 0;
995 LeaveCriticalSection(&cond->waiters_count_lock);
998 if (!SetEvent(cond->events[SIGNAL]))
999 THROWF(system_error, 0, "SetEvent failed");
1001 xbt_os_thread_yield();
1004 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1008 EnterCriticalSection(&cond->waiters_count_lock);
1009 have_waiters = cond->waiters_count > 0;
1010 LeaveCriticalSection(&cond->waiters_count_lock);
1013 SetEvent(cond->events[BROADCAST]);
1016 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1023 if (!CloseHandle(cond->events[SIGNAL]))
1026 if (!CloseHandle(cond->events[BROADCAST]))
1029 DeleteCriticalSection(&cond->waiters_count_lock);
1034 THROWF(system_error, 0, "Error while destroying the condition");
1037 typedef struct xbt_os_sem_ {
1040 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1044 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1047 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1051 if (value > INT_MAX)
1052 THROWF(arg_error, value,
1053 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1056 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1058 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1059 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1060 strerror(GetLastError()));
1066 InitializeCriticalSection(&(res->value_lock));
1071 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1074 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1077 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1078 THROWF(system_error, GetLastError(),
1079 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1080 EnterCriticalSection(&(sem->value_lock));
1082 LeaveCriticalSection(&(sem->value_lock));
1085 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1089 double end = timeout + xbt_os_time();
1092 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1095 xbt_os_sem_acquire(sem);
1096 } else { /* timeout can be zero <-> try acquire ) */
1099 seconds = (long) floor(end);
1100 milliseconds = (long) ((end - seconds) * 1000);
1101 milliseconds += (seconds * 1000);
1103 switch (WaitForSingleObject(sem->h, milliseconds)) {
1105 EnterCriticalSection(&(sem->value_lock));
1107 LeaveCriticalSection(&(sem->value_lock));
1111 THROWF(timeout_error, GetLastError(),
1112 "semaphore %p wasn't signaled before timeout (%f)", sem,
1117 THROWF(system_error, GetLastError(),
1118 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1119 strerror(GetLastError()));
1124 void xbt_os_sem_release(xbt_os_sem_t sem)
1127 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1129 if (!ReleaseSemaphore(sem->h, 1, NULL))
1130 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1131 strerror(GetLastError()));
1132 EnterCriticalSection(&(sem->value_lock));
1134 LeaveCriticalSection(&(sem->value_lock));
1137 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1140 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1142 if (!CloseHandle(sem->h))
1143 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1144 strerror(GetLastError()));
1146 DeleteCriticalSection(&(sem->value_lock));
1152 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1155 THROWF(arg_error, EINVAL,
1156 "Cannot get the value of the NULL semaphore");
1158 EnterCriticalSection(&(sem->value_lock));
1159 *svalue = sem->value;
1160 LeaveCriticalSection(&(sem->value_lock));
1167 /** @brief Returns the amount of cores on the current host */
1168 int xbt_os_get_numcores(void) {
1170 SYSTEM_INFO sysinfo;
1171 GetSystemInfo(&sysinfo);
1172 return sysinfo.dwNumberOfProcessors;
1178 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1179 sysctl(nm, 2, &count, &len, NULL, 0);
1183 sysctl(nm, 2, &count, &len, NULL, 0);
1184 if(count < 1) { count = 1; }
1188 return sysconf(_SC_NPROCESSORS_ONLN);
1193 /***** reentrant mutexes *****/
1194 typedef struct xbt_os_rmutex_ {
1195 xbt_os_mutex_t mutex;
1196 xbt_os_thread_t owner;
1198 } s_xbt_os_rmutex_t;
1200 void xbt_os_thread_set_extra_data(void *data)
1202 xbt_os_thread_self()->extra_data = data;
1205 void *xbt_os_thread_get_extra_data(void)
1207 return xbt_os_thread_self()->extra_data;
1210 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1212 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1213 rmutex->mutex = xbt_os_mutex_init();
1214 rmutex->owner = NULL;
1219 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1221 xbt_os_thread_t self = xbt_os_thread_self();
1224 /* the thread module is not initialized yet */
1225 rmutex->owner = NULL;
1229 if (self != rmutex->owner) {
1230 xbt_os_mutex_acquire(rmutex->mutex);
1231 rmutex->owner = self;
1238 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1240 if (rmutex->owner == NULL) {
1241 /* the thread module was not initialized */
1245 xbt_assert(rmutex->owner == xbt_os_thread_self());
1247 if (--rmutex->count == 0) {
1248 rmutex->owner = NULL;
1249 xbt_os_mutex_release(rmutex->mutex);
1253 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1255 xbt_os_mutex_destroy(rmutex->mutex);