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-2014. 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 "internal_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 /* defaults attribute for pthreads */
58 //FIXME: find where to put this
59 static pthread_attr_t thread_attr;
61 /* frees the xbt_os_thread_t corresponding to the current thread */
62 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
64 if (thread == main_thread) /* just killed main thread */
67 free(thread->running_ctx);
72 /* callback: context fetching */
73 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
75 return xbt_os_thread_self()->running_ctx;
78 /* callback: termination */
79 static void _os_thread_ex_terminate(xbt_ex_t * e)
83 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
86 void xbt_os_thread_mod_preinit(void)
90 if (thread_mod_inited)
93 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
94 THROWF(system_error, errcode,
95 "pthread_key_create failed for xbt_self_thread_key");
97 main_thread = xbt_new(s_xbt_os_thread_t, 1);
98 main_thread->name = (char *) "main";
99 main_thread->start_routine = NULL;
100 main_thread->param = NULL;
101 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
102 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
104 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
105 THROWF(system_error, errcode,
106 "pthread_setspecific failed for xbt_self_thread_key");
108 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
109 __xbt_ex_terminate = _os_thread_ex_terminate;
111 pthread_attr_init(&thread_attr);
113 thread_mod_inited = 1;
115 #ifndef HAVE_SEM_INIT
116 next_sem_ID_lock = xbt_os_mutex_init();
121 void xbt_os_thread_mod_postexit(void)
123 /* FIXME: don't try to free our key on shutdown.
124 Valgrind detects no leak if we don't, and whine if we try to */
127 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
128 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
129 free(main_thread->running_ctx);
132 thread_mod_inited = 0;
133 #ifndef HAVE_SEM_INIT
134 xbt_os_mutex_destroy(next_sem_ID_lock);
137 /* Restore the default exception setup */
138 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
139 __xbt_ex_terminate = &__xbt_ex_terminate_default;
142 /* this function is critical to tesh+mmalloc, don't mess with it */
143 int xbt_os_thread_atfork(void (*prepare)(void),
144 void (*parent)(void), void (*child)(void))
147 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
149 return pthread_atfork(prepare, parent, child);
153 static void *wrapper_start_routine(void *s)
155 xbt_os_thread_t t = s;
158 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
159 THROWF(system_error, errcode,
160 "pthread_setspecific failed for xbt_self_thread_key");
162 void *res = t->start_routine(t->param);
164 xbt_os_thread_free_thread_data(t);
169 xbt_os_thread_t xbt_os_thread_create(const char *name,
170 pvoid_f_pvoid_t start_routine,
176 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
177 res_thread->detached = 0;
178 res_thread->name = xbt_strdup(name);
179 res_thread->start_routine = start_routine;
180 res_thread->param = param;
181 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
182 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
183 res_thread->extra_data = extra_data;
185 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
186 wrapper_start_routine, res_thread)))
187 THROWF(system_error, errcode,
188 "pthread_create failed: %s", strerror(errcode));
196 void xbt_os_thread_setstacksize(int stack_size)
198 size_t alignment[] = {
200 #ifdef PTHREAD_STACK_MIN
210 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
213 res = pthread_attr_setstacksize(&thread_attr, sz);
215 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
216 /* Invalid size, try again with next multiple of alignment[i]. */
217 size_t rem = sz % alignment[i];
218 if (rem != 0 || sz == 0) {
219 size_t sz2 = sz - rem + alignment[i];
220 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
223 res = pthread_attr_setstacksize(&thread_attr, sz);
228 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
230 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
233 void xbt_os_thread_setguardsize(int guard_size)
235 size_t sz = guard_size;
236 int res = pthread_attr_setguardsize(&thread_attr, sz);
238 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
241 const char *xbt_os_thread_name(xbt_os_thread_t t)
246 const char *xbt_os_thread_self_name(void)
248 xbt_os_thread_t me = xbt_os_thread_self();
249 return me ? me->name : "main";
252 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
257 if ((errcode = pthread_join(thread->t, thread_return)))
258 THROWF(system_error, errcode, "pthread_join failed: %s",
260 xbt_os_thread_free_thread_data(thread);
263 void xbt_os_thread_exit(int *retval)
265 pthread_exit(retval);
268 xbt_os_thread_t xbt_os_thread_self(void)
272 if (!thread_mod_inited)
275 res = pthread_getspecific(xbt_self_thread_key);
280 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
283 if ((errcode = pthread_key_create(key, NULL)))
284 THROWF(system_error, errcode, "pthread_key_create failed");
287 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
290 if ((errcode = pthread_setspecific(key, value)))
291 THROWF(system_error, errcode, "pthread_setspecific failed");
294 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
295 return pthread_getspecific(key);
298 void xbt_os_thread_detach(xbt_os_thread_t thread)
300 thread->detached = 1;
301 pthread_detach(thread->t);
305 void xbt_os_thread_yield(void)
310 void xbt_os_thread_cancel(xbt_os_thread_t t)
312 pthread_cancel(t->t);
315 /****** mutex related functions ******/
316 typedef struct xbt_os_mutex_ {
317 /* KEEP IT IN SYNC WITH xbt_thread.c */
324 xbt_os_mutex_t xbt_os_mutex_init(void)
326 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
329 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
330 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
336 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
340 if ((errcode = pthread_mutex_lock(&(mutex->m))))
341 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
342 mutex, strerror(errcode));
346 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
351 xbt_os_mutex_acquire(mutex);
353 } else if (delay == 0) {
354 errcode = pthread_mutex_trylock(&(mutex->m));
360 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
362 THROWF(system_error, errcode,
363 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
370 #ifdef HAVE_MUTEX_TIMEDLOCK
371 struct timespec ts_end;
372 double end = delay + xbt_os_time();
374 ts_end.tv_sec = (time_t) floor(end);
375 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
376 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
378 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
380 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
381 double start = xbt_os_time();
383 errcode = pthread_mutex_trylock(&(mutex->m));
384 if (errcode == EBUSY)
385 xbt_os_thread_yield();
386 } while (errcode == EBUSY && xbt_os_time() - start < delay);
388 if (errcode == EBUSY)
391 #endif /* HAVE_MUTEX_TIMEDLOCK */
398 THROWF(timeout_error, delay,
399 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
402 THROWF(system_error, errcode,
403 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
409 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
413 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
414 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
415 mutex, strerror(errcode));
418 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
425 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
426 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
427 mutex, strerror(errcode));
431 /***** condition related functions *****/
432 typedef struct xbt_os_cond_ {
433 /* KEEP IT IN SYNC WITH xbt_thread.c */
437 xbt_os_cond_t xbt_os_cond_init(void)
439 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
441 if ((errcode = pthread_cond_init(&(res->c), NULL)))
442 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
448 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
451 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
452 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
453 cond, mutex, strerror(errcode));
457 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
461 struct timespec ts_end;
462 double end = delay + xbt_os_time();
465 xbt_os_cond_wait(cond, mutex);
467 ts_end.tv_sec = (time_t) floor(end);
468 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
469 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
472 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
476 THROWF(timeout_error, errcode,
477 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
480 THROWF(system_error, errcode,
481 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
482 delay, strerror(errcode));
487 void xbt_os_cond_signal(xbt_os_cond_t cond)
490 if ((errcode = pthread_cond_signal(&(cond->c))))
491 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
492 cond, strerror(errcode));
495 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
498 if ((errcode = pthread_cond_broadcast(&(cond->c))))
499 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
500 cond, strerror(errcode));
503 void xbt_os_cond_destroy(xbt_os_cond_t cond)
510 if ((errcode = pthread_cond_destroy(&(cond->c))))
511 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
512 cond, strerror(errcode));
516 void *xbt_os_thread_getparam(void)
518 xbt_os_thread_t t = xbt_os_thread_self();
519 return t ? t->param : NULL;
522 typedef struct xbt_os_sem_ {
523 #ifndef HAVE_SEM_INIT
531 #define SEM_FAILED (-1)
534 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
536 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
538 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
539 * Any attempt to use it leads to ENOSYS (function not implemented).
540 * If such a prehistoric system is detected, do the job with sem_open instead
543 if (sem_init(&(res->s), 0, value) != 0)
544 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
547 #else /* damn, no sem_init(). Reimplement it */
549 xbt_os_mutex_acquire(next_sem_ID_lock);
550 res->name = bprintf("/%d", ++next_sem_ID);
551 xbt_os_mutex_release(next_sem_ID_lock);
553 res->ps = sem_open(res->name, O_CREAT, 0644, value);
554 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
555 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
556 res->name[13] = '\0';
557 res->ps = sem_open(res->name, O_CREAT, 0644, value);
559 if ((res->ps == (sem_t *) SEM_FAILED))
560 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
562 /* Remove the name from the semaphore namespace: we never join on it */
563 if (sem_unlink(res->name) < 0)
564 THROWF(system_error, errno, "sem_unlink() failed: %s",
572 void xbt_os_sem_acquire(xbt_os_sem_t sem)
575 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
576 if (sem_wait(sem->ps) < 0)
577 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
580 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
585 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
588 xbt_os_sem_acquire(sem);
589 } else if (delay == 0) {
590 errcode = sem_trywait(sem->ps);
596 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
598 THROWF(system_error, errcode,
599 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
605 struct timespec ts_end;
606 double end = delay + xbt_os_time();
608 ts_end.tv_sec = (time_t) floor(end);
609 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
610 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
611 errcode = sem_timedwait(sem->s, &ts_end);
613 #else /* Okay, reimplement this function then */
614 double start = xbt_os_time();
616 errcode = sem_trywait(sem->ps);
617 if (errcode == EBUSY)
618 xbt_os_thread_yield();
619 } while (errcode == EBUSY && xbt_os_time() - start < delay);
621 if (errcode == EBUSY)
630 THROWF(timeout_error, delay,
631 "semaphore %p wasn't signaled before timeout (%f)", sem,
635 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
636 delay, strerror(errcode));
641 void xbt_os_sem_release(xbt_os_sem_t sem)
644 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
646 if (sem_post(sem->ps) < 0)
647 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
650 void xbt_os_sem_destroy(xbt_os_sem_t sem)
653 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
656 if (sem_destroy(sem->ps) < 0)
657 THROWF(system_error, errno, "sem_destroy() failed: %s",
660 if (sem_close(sem->ps) < 0)
661 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
668 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
671 THROWF(arg_error, EINVAL,
672 "Cannot get the value of the NULL semaphore");
674 if (sem_getvalue(&(sem->s), svalue) < 0)
675 THROWF(system_error, errno, "sem_getvalue() failed: %s",
679 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
681 #elif defined(_XBT_WIN32)
685 typedef struct xbt_os_thread_ {
687 HANDLE handle; /* the win thread handle */
688 unsigned long id; /* the win thread id */
689 pvoid_f_pvoid_t start_routine;
694 /* so we can specify the size of the stack of the threads */
695 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
696 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
699 /* the default size of the stack of the threads (in bytes)*/
700 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
701 static int stack_size=0;
702 /* key to the TLS containing the xbt_os_thread_t structure */
703 static unsigned long xbt_self_thread_key;
705 void xbt_os_thread_mod_preinit(void)
707 xbt_self_thread_key = TlsAlloc();
710 void xbt_os_thread_mod_postexit(void)
713 if (!TlsFree(xbt_self_thread_key))
714 THROWF(system_error, (int) GetLastError(),
715 "TlsFree() failed to cleanup the thread submodule");
718 int xbt_os_thread_atfork(void (*prepare)(void),
719 void (*parent)(void), void (*child)(void))
724 static DWORD WINAPI wrapper_start_routine(void *s)
726 xbt_os_thread_t t = (xbt_os_thread_t) s;
729 if (!TlsSetValue(xbt_self_thread_key, t))
730 THROWF(system_error, (int) GetLastError(),
731 "TlsSetValue of data describing the created thread failed");
733 rv = (DWORD *) ((t->start_routine) (t->param));
740 xbt_os_thread_t xbt_os_thread_create(const char *name,
741 pvoid_f_pvoid_t start_routine,
746 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
748 t->name = xbt_strdup(name);
749 t->start_routine = start_routine;
751 t->extra_data = extra_data;
752 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
753 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
754 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
758 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
764 void xbt_os_thread_setstacksize(int size)
769 void xbt_os_thread_setguardsize(int size)
771 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
774 const char *xbt_os_thread_name(xbt_os_thread_t t)
779 const char *xbt_os_thread_self_name(void)
781 xbt_os_thread_t t = xbt_os_thread_self();
782 return t ? t->name : "main";
785 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
788 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
789 THROWF(system_error, (int) GetLastError(),
790 "WaitForSingleObject failed");
794 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
795 THROWF(system_error, (int) GetLastError(),
796 "GetExitCodeThread failed");
799 CloseHandle(thread->handle);
806 void xbt_os_thread_exit(int *retval)
814 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
819 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
821 if (!TlsSetValue(key, value))
822 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
825 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
826 return TlsGetValue(key);
829 void xbt_os_thread_detach(xbt_os_thread_t thread)
835 xbt_os_thread_t xbt_os_thread_self(void)
837 return TlsGetValue(xbt_self_thread_key);
840 void *xbt_os_thread_getparam(void)
842 xbt_os_thread_t t = xbt_os_thread_self();
847 void xbt_os_thread_yield(void)
852 void xbt_os_thread_cancel(xbt_os_thread_t t)
854 if (!TerminateThread(t->handle, 0))
855 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
858 /****** mutex related functions ******/
859 typedef struct xbt_os_mutex_ {
860 /* KEEP IT IN SYNC WITH xbt_thread.c */
861 CRITICAL_SECTION lock;
864 xbt_os_mutex_t xbt_os_mutex_init(void)
866 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
868 /* initialize the critical section object */
869 InitializeCriticalSection(&(res->lock));
874 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
876 EnterCriticalSection(&mutex->lock);
879 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
884 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
887 LeaveCriticalSection(&mutex->lock);
891 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
897 DeleteCriticalSection(&mutex->lock);
901 /***** condition related functions *****/
902 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
908 typedef struct xbt_os_cond_ {
909 /* KEEP IT IN SYNC WITH xbt_thread.c */
910 HANDLE events[MAX_EVENTS];
912 unsigned int waiters_count; /* the number of waiters */
913 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
916 xbt_os_cond_t xbt_os_cond_init(void)
919 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
921 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
923 /* initialize the critical section object */
924 InitializeCriticalSection(&res->waiters_count_lock);
926 res->waiters_count = 0;
928 /* Create an auto-reset event */
929 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
931 if (!res->events[SIGNAL]) {
932 DeleteCriticalSection(&res->waiters_count_lock);
934 THROWF(system_error, 0, "CreateEvent failed for the signals");
937 /* Create a manual-reset event. */
938 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
940 if (!res->events[BROADCAST]) {
942 DeleteCriticalSection(&res->waiters_count_lock);
943 CloseHandle(res->events[SIGNAL]);
945 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
951 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
954 unsigned long wait_result;
957 /* lock the threads counter and increment it */
958 EnterCriticalSection(&cond->waiters_count_lock);
959 cond->waiters_count++;
960 LeaveCriticalSection(&cond->waiters_count_lock);
962 /* unlock the mutex associate with the condition */
963 LeaveCriticalSection(&mutex->lock);
965 /* wait for a signal (broadcast or no) */
966 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
968 if (wait_result == WAIT_FAILED)
969 THROWF(system_error, 0,
970 "WaitForMultipleObjects failed, so we cannot wait on the condition");
972 /* we have a signal lock the condition */
973 EnterCriticalSection(&cond->waiters_count_lock);
974 cond->waiters_count--;
976 /* it's the last waiter or it's a broadcast ? */
977 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
978 && (cond->waiters_count == 0));
980 LeaveCriticalSection(&cond->waiters_count_lock);
982 /* yes it's the last waiter or it's a broadcast
983 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
987 if (!ResetEvent(cond->events[BROADCAST]))
988 THROWF(system_error, 0, "ResetEvent failed");
990 /* relock the mutex associated with the condition in accordance with the posix thread specification */
991 EnterCriticalSection(&mutex->lock);
994 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
998 unsigned long wait_result = WAIT_TIMEOUT;
1000 unsigned long end = (unsigned long) (delay * 1000);
1004 xbt_os_cond_wait(cond, mutex);
1006 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1007 &(mutex->lock), end);
1009 /* lock the threads counter and increment it */
1010 EnterCriticalSection(&cond->waiters_count_lock);
1011 cond->waiters_count++;
1012 LeaveCriticalSection(&cond->waiters_count_lock);
1014 /* unlock the mutex associate with the condition */
1015 LeaveCriticalSection(&mutex->lock);
1016 /* wait for a signal (broadcast or no) */
1018 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1020 switch (wait_result) {
1022 THROWF(timeout_error, GetLastError(),
1023 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1024 cond, mutex, delay);
1026 THROWF(system_error, GetLastError(),
1027 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1030 /* we have a signal lock the condition */
1031 EnterCriticalSection(&cond->waiters_count_lock);
1032 cond->waiters_count--;
1034 /* it's the last waiter or it's a broadcast ? */
1035 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1036 && (cond->waiters_count == 0));
1038 LeaveCriticalSection(&cond->waiters_count_lock);
1040 /* yes it's the last waiter or it's a broadcast
1041 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1045 if (!ResetEvent(cond->events[BROADCAST]))
1046 THROWF(system_error, 0, "ResetEvent failed");
1048 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1049 EnterCriticalSection(&mutex->lock);
1051 /*THROW_UNIMPLEMENTED; */
1054 void xbt_os_cond_signal(xbt_os_cond_t cond)
1058 EnterCriticalSection(&cond->waiters_count_lock);
1059 have_waiters = cond->waiters_count > 0;
1060 LeaveCriticalSection(&cond->waiters_count_lock);
1063 if (!SetEvent(cond->events[SIGNAL]))
1064 THROWF(system_error, 0, "SetEvent failed");
1066 xbt_os_thread_yield();
1069 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1073 EnterCriticalSection(&cond->waiters_count_lock);
1074 have_waiters = cond->waiters_count > 0;
1075 LeaveCriticalSection(&cond->waiters_count_lock);
1078 SetEvent(cond->events[BROADCAST]);
1081 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1088 if (!CloseHandle(cond->events[SIGNAL]))
1091 if (!CloseHandle(cond->events[BROADCAST]))
1094 DeleteCriticalSection(&cond->waiters_count_lock);
1099 THROWF(system_error, 0, "Error while destroying the condition");
1102 typedef struct xbt_os_sem_ {
1105 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1109 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1112 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1116 if (value > INT_MAX)
1117 THROWF(arg_error, value,
1118 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1121 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1123 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1124 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1125 strerror(GetLastError()));
1131 InitializeCriticalSection(&(res->value_lock));
1136 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1139 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1142 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1143 THROWF(system_error, GetLastError(),
1144 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1145 EnterCriticalSection(&(sem->value_lock));
1147 LeaveCriticalSection(&(sem->value_lock));
1150 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1154 double end = timeout + xbt_os_time();
1157 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1160 xbt_os_sem_acquire(sem);
1161 } else { /* timeout can be zero <-> try acquire ) */
1164 seconds = (long) floor(end);
1165 milliseconds = (long) ((end - seconds) * 1000);
1166 milliseconds += (seconds * 1000);
1168 switch (WaitForSingleObject(sem->h, milliseconds)) {
1170 EnterCriticalSection(&(sem->value_lock));
1172 LeaveCriticalSection(&(sem->value_lock));
1176 THROWF(timeout_error, GetLastError(),
1177 "semaphore %p wasn't signaled before timeout (%f)", sem,
1182 THROWF(system_error, GetLastError(),
1183 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1184 strerror(GetLastError()));
1189 void xbt_os_sem_release(xbt_os_sem_t sem)
1192 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1194 if (!ReleaseSemaphore(sem->h, 1, NULL))
1195 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1196 strerror(GetLastError()));
1197 EnterCriticalSection(&(sem->value_lock));
1199 LeaveCriticalSection(&(sem->value_lock));
1202 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1205 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1207 if (!CloseHandle(sem->h))
1208 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1209 strerror(GetLastError()));
1211 DeleteCriticalSection(&(sem->value_lock));
1217 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1220 THROWF(arg_error, EINVAL,
1221 "Cannot get the value of the NULL semaphore");
1223 EnterCriticalSection(&(sem->value_lock));
1224 *svalue = sem->value;
1225 LeaveCriticalSection(&(sem->value_lock));
1232 /** @brief Returns the amount of cores on the current host */
1233 int xbt_os_get_numcores(void) {
1235 SYSTEM_INFO sysinfo;
1236 GetSystemInfo(&sysinfo);
1237 return sysinfo.dwNumberOfProcessors;
1243 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1244 sysctl(nm, 2, &count, &len, NULL, 0);
1248 sysctl(nm, 2, &count, &len, NULL, 0);
1249 if(count < 1) { count = 1; }
1253 return sysconf(_SC_NPROCESSORS_ONLN);
1258 /***** reentrant mutexes *****/
1259 typedef struct xbt_os_rmutex_ {
1260 xbt_os_mutex_t mutex;
1261 xbt_os_thread_t owner;
1263 } s_xbt_os_rmutex_t;
1265 void xbt_os_thread_set_extra_data(void *data)
1267 xbt_os_thread_self()->extra_data = data;
1270 void *xbt_os_thread_get_extra_data(void)
1272 xbt_os_thread_t self = xbt_os_thread_self();
1273 return self? self->extra_data : NULL;
1276 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1278 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1279 rmutex->mutex = xbt_os_mutex_init();
1280 rmutex->owner = NULL;
1285 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1287 xbt_os_thread_t self = xbt_os_thread_self();
1290 /* the thread module is not initialized yet */
1291 rmutex->owner = NULL;
1295 if (self != rmutex->owner) {
1296 xbt_os_mutex_acquire(rmutex->mutex);
1297 rmutex->owner = self;
1304 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1306 if (rmutex->owner == NULL) {
1307 /* the thread module was not initialized */
1311 xbt_assert(rmutex->owner == xbt_os_thread_self());
1313 if (--rmutex->count == 0) {
1314 rmutex->owner = NULL;
1315 xbt_os_mutex_release(rmutex->mutex);
1319 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1321 xbt_os_mutex_destroy(rmutex->mutex);