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 ************************************ */
28 #include <semaphore.h>
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 /* defaults attribute for pthreads */
57 //FIXME: find where to put this
58 static pthread_attr_t thread_attr;
60 /* frees the xbt_os_thread_t corresponding to the current thread */
61 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
63 if (thread == main_thread) /* just killed main thread */
66 free(thread->running_ctx);
71 /* callback: context fetching */
72 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
74 return xbt_os_thread_self()->running_ctx;
77 /* callback: termination */
78 static void _os_thread_ex_terminate(xbt_ex_t * e)
82 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
85 void xbt_os_thread_mod_preinit(void)
89 if (thread_mod_inited)
92 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
93 THROWF(system_error, errcode,
94 "pthread_key_create failed for xbt_self_thread_key");
96 main_thread = xbt_new(s_xbt_os_thread_t, 1);
97 main_thread->name = (char *) "main";
98 main_thread->start_routine = NULL;
99 main_thread->param = NULL;
100 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
101 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
103 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
104 THROWF(system_error, errcode,
105 "pthread_setspecific failed for xbt_self_thread_key");
107 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
108 __xbt_ex_terminate = _os_thread_ex_terminate;
110 pthread_attr_init(&thread_attr);
112 thread_mod_inited = 1;
114 #ifndef HAVE_SEM_INIT
115 next_sem_ID_lock = xbt_os_mutex_init();
120 void xbt_os_thread_mod_postexit(void)
122 /* FIXME: don't try to free our key on shutdown.
123 Valgrind detects no leak if we don't, and whine if we try to */
126 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
127 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
128 free(main_thread->running_ctx);
131 thread_mod_inited = 0;
132 #ifndef HAVE_SEM_INIT
133 xbt_os_mutex_destroy(next_sem_ID_lock);
136 /* Restore the default exception setup */
137 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
138 __xbt_ex_terminate = &__xbt_ex_terminate_default;
141 /* this function is critical to tesh+mmalloc, don't mess with it */
142 int xbt_os_thread_atfork(void (*prepare)(void),
143 void (*parent)(void), void (*child)(void))
146 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
148 return pthread_atfork(prepare, parent, child);
152 static void *wrapper_start_routine(void *s)
154 xbt_os_thread_t t = s;
157 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
158 THROWF(system_error, errcode,
159 "pthread_setspecific failed for xbt_self_thread_key");
161 void *res = t->start_routine(t->param);
163 xbt_os_thread_free_thread_data(t);
168 xbt_os_thread_t xbt_os_thread_create(const char *name,
169 pvoid_f_pvoid_t start_routine,
175 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
176 res_thread->detached = 0;
177 res_thread->name = xbt_strdup(name);
178 res_thread->start_routine = start_routine;
179 res_thread->param = param;
180 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
181 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
182 res_thread->extra_data = extra_data;
184 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
185 wrapper_start_routine, res_thread)))
186 THROWF(system_error, errcode,
187 "pthread_create failed: %s", strerror(errcode));
196 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
197 pthread_t pthread = thread->t;
201 CPU_SET(cpu, &cpuset);
202 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
207 void xbt_os_thread_setstacksize(int stack_size)
209 size_t alignment[] = {
211 #ifdef PTHREAD_STACK_MIN
221 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
224 res = pthread_attr_setstacksize(&thread_attr, sz);
226 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
227 /* Invalid size, try again with next multiple of alignment[i]. */
228 size_t rem = sz % alignment[i];
229 if (rem != 0 || sz == 0) {
230 size_t sz2 = sz - rem + alignment[i];
231 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
234 res = pthread_attr_setstacksize(&thread_attr, sz);
239 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
241 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
244 void xbt_os_thread_setguardsize(int guard_size)
247 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
249 size_t sz = guard_size;
250 int res = pthread_attr_setguardsize(&thread_attr, sz);
252 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
256 const char *xbt_os_thread_name(xbt_os_thread_t t)
261 const char *xbt_os_thread_self_name(void)
263 xbt_os_thread_t me = xbt_os_thread_self();
264 return me ? me->name : "main";
267 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
272 if ((errcode = pthread_join(thread->t, thread_return)))
273 THROWF(system_error, errcode, "pthread_join failed: %s",
275 xbt_os_thread_free_thread_data(thread);
278 void xbt_os_thread_exit(int *retval)
280 pthread_exit(retval);
283 xbt_os_thread_t xbt_os_thread_self(void)
287 if (!thread_mod_inited)
290 res = pthread_getspecific(xbt_self_thread_key);
295 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
298 if ((errcode = pthread_key_create(key, NULL)))
299 THROWF(system_error, errcode, "pthread_key_create failed");
302 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
305 if ((errcode = pthread_setspecific(key, value)))
306 THROWF(system_error, errcode, "pthread_setspecific failed");
309 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
310 return pthread_getspecific(key);
313 void xbt_os_thread_detach(xbt_os_thread_t thread)
315 thread->detached = 1;
316 pthread_detach(thread->t);
320 void xbt_os_thread_yield(void)
325 void xbt_os_thread_cancel(xbt_os_thread_t t)
327 pthread_cancel(t->t);
330 /****** mutex related functions ******/
331 typedef struct xbt_os_mutex_ {
332 /* KEEP IT IN SYNC WITH xbt_thread.c */
339 xbt_os_mutex_t xbt_os_mutex_init(void)
341 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
344 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
345 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
351 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
355 if ((errcode = pthread_mutex_lock(&(mutex->m))))
356 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
357 mutex, strerror(errcode));
361 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
366 xbt_os_mutex_acquire(mutex);
368 } else if (delay == 0) {
369 errcode = pthread_mutex_trylock(&(mutex->m));
375 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
377 THROWF(system_error, errcode,
378 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
385 #ifdef HAVE_MUTEX_TIMEDLOCK
386 struct timespec ts_end;
387 double end = delay + xbt_os_time();
389 ts_end.tv_sec = (time_t) floor(end);
390 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
391 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
393 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
395 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
396 double start = xbt_os_time();
398 errcode = pthread_mutex_trylock(&(mutex->m));
399 if (errcode == EBUSY)
400 xbt_os_thread_yield();
401 } while (errcode == EBUSY && xbt_os_time() - start < delay);
403 if (errcode == EBUSY)
406 #endif /* HAVE_MUTEX_TIMEDLOCK */
413 THROWF(timeout_error, delay,
414 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
417 THROWF(system_error, errcode,
418 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
424 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
428 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
429 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
430 mutex, strerror(errcode));
433 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
440 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
441 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
442 mutex, strerror(errcode));
446 /***** condition related functions *****/
447 typedef struct xbt_os_cond_ {
448 /* KEEP IT IN SYNC WITH xbt_thread.c */
452 xbt_os_cond_t xbt_os_cond_init(void)
454 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
456 if ((errcode = pthread_cond_init(&(res->c), NULL)))
457 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
463 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
466 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
467 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
468 cond, mutex, strerror(errcode));
472 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
476 struct timespec ts_end;
477 double end = delay + xbt_os_time();
480 xbt_os_cond_wait(cond, mutex);
482 ts_end.tv_sec = (time_t) floor(end);
483 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
484 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
487 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
491 THROWF(timeout_error, errcode,
492 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
495 THROWF(system_error, errcode,
496 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
497 delay, strerror(errcode));
502 void xbt_os_cond_signal(xbt_os_cond_t cond)
505 if ((errcode = pthread_cond_signal(&(cond->c))))
506 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
507 cond, strerror(errcode));
510 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
513 if ((errcode = pthread_cond_broadcast(&(cond->c))))
514 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
515 cond, strerror(errcode));
518 void xbt_os_cond_destroy(xbt_os_cond_t cond)
525 if ((errcode = pthread_cond_destroy(&(cond->c))))
526 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
527 cond, strerror(errcode));
531 void *xbt_os_thread_getparam(void)
533 xbt_os_thread_t t = xbt_os_thread_self();
534 return t ? t->param : NULL;
537 typedef struct xbt_os_sem_ {
538 #ifndef HAVE_SEM_INIT
546 #define SEM_FAILED (-1)
549 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
551 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
553 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
554 * Any attempt to use it leads to ENOSYS (function not implemented).
555 * If such a prehistoric system is detected, do the job with sem_open instead
558 if (sem_init(&(res->s), 0, value) != 0)
559 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
562 #else /* damn, no sem_init(). Reimplement it */
564 xbt_os_mutex_acquire(next_sem_ID_lock);
565 res->name = bprintf("/%d", ++next_sem_ID);
566 xbt_os_mutex_release(next_sem_ID_lock);
568 res->ps = sem_open(res->name, O_CREAT, 0644, value);
569 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
570 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
571 res->name[13] = '\0';
572 res->ps = sem_open(res->name, O_CREAT, 0644, value);
574 if ((res->ps == (sem_t *) SEM_FAILED))
575 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
577 /* Remove the name from the semaphore namespace: we never join on it */
578 if (sem_unlink(res->name) < 0)
579 THROWF(system_error, errno, "sem_unlink() failed: %s",
587 void xbt_os_sem_acquire(xbt_os_sem_t sem)
590 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
591 if (sem_wait(sem->ps) < 0)
592 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
595 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
600 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
603 xbt_os_sem_acquire(sem);
604 } else if (delay == 0) {
605 errcode = sem_trywait(sem->ps);
611 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
613 THROWF(system_error, errcode,
614 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
620 struct timespec ts_end;
621 double end = delay + xbt_os_time();
623 ts_end.tv_sec = (time_t) floor(end);
624 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
625 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
626 errcode = sem_timedwait(sem->s, &ts_end);
628 #else /* Okay, reimplement this function then */
629 double start = xbt_os_time();
631 errcode = sem_trywait(sem->ps);
632 if (errcode == EBUSY)
633 xbt_os_thread_yield();
634 } while (errcode == EBUSY && xbt_os_time() - start < delay);
636 if (errcode == EBUSY)
645 THROWF(timeout_error, delay,
646 "semaphore %p wasn't signaled before timeout (%f)", sem,
650 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
651 delay, strerror(errcode));
656 void xbt_os_sem_release(xbt_os_sem_t sem)
659 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
661 if (sem_post(sem->ps) < 0)
662 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
665 void xbt_os_sem_destroy(xbt_os_sem_t sem)
668 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
671 if (sem_destroy(sem->ps) < 0)
672 THROWF(system_error, errno, "sem_destroy() failed: %s",
675 if (sem_close(sem->ps) < 0)
676 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
683 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
686 THROWF(arg_error, EINVAL,
687 "Cannot get the value of the NULL semaphore");
689 if (sem_getvalue(&(sem->s), svalue) < 0)
690 THROWF(system_error, errno, "sem_getvalue() failed: %s",
694 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
696 #elif defined(_XBT_WIN32)
700 typedef struct xbt_os_thread_ {
702 HANDLE handle; /* the win thread handle */
703 unsigned long id; /* the win thread id */
704 pvoid_f_pvoid_t start_routine;
709 /* so we can specify the size of the stack of the threads */
710 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
711 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
714 /* the default size of the stack of the threads (in bytes)*/
715 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
716 static int stack_size=0;
717 /* key to the TLS containing the xbt_os_thread_t structure */
718 static unsigned long xbt_self_thread_key;
720 void xbt_os_thread_mod_preinit(void)
722 xbt_self_thread_key = TlsAlloc();
725 void xbt_os_thread_mod_postexit(void)
728 if (!TlsFree(xbt_self_thread_key))
729 THROWF(system_error, (int) GetLastError(),
730 "TlsFree() failed to cleanup the thread submodule");
733 int xbt_os_thread_atfork(void (*prepare)(void),
734 void (*parent)(void), void (*child)(void))
739 static DWORD WINAPI wrapper_start_routine(void *s)
741 xbt_os_thread_t t = (xbt_os_thread_t) s;
744 if (!TlsSetValue(xbt_self_thread_key, t))
745 THROWF(system_error, (int) GetLastError(),
746 "TlsSetValue of data describing the created thread failed");
748 rv = (DWORD *) ((t->start_routine) (t->param));
755 xbt_os_thread_t xbt_os_thread_create(const char *name,
756 pvoid_f_pvoid_t start_routine,
761 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
763 t->name = xbt_strdup(name);
764 t->start_routine = start_routine;
766 t->extra_data = extra_data;
767 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
768 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
769 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
773 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
779 void xbt_os_thread_setstacksize(int size)
784 void xbt_os_thread_setguardsize(int size)
786 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
789 const char *xbt_os_thread_name(xbt_os_thread_t t)
794 const char *xbt_os_thread_self_name(void)
796 xbt_os_thread_t t = xbt_os_thread_self();
797 return t ? t->name : "main";
800 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
803 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
804 THROWF(system_error, (int) GetLastError(),
805 "WaitForSingleObject failed");
809 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
810 THROWF(system_error, (int) GetLastError(),
811 "GetExitCodeThread failed");
814 CloseHandle(thread->handle);
821 void xbt_os_thread_exit(int *retval)
829 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
834 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
836 if (!TlsSetValue(key, value))
837 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
840 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
841 return TlsGetValue(key);
844 void xbt_os_thread_detach(xbt_os_thread_t thread)
850 xbt_os_thread_t xbt_os_thread_self(void)
852 return TlsGetValue(xbt_self_thread_key);
855 void *xbt_os_thread_getparam(void)
857 xbt_os_thread_t t = xbt_os_thread_self();
862 void xbt_os_thread_yield(void)
867 void xbt_os_thread_cancel(xbt_os_thread_t t)
869 if (!TerminateThread(t->handle, 0))
870 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
873 /****** mutex related functions ******/
874 typedef struct xbt_os_mutex_ {
875 /* KEEP IT IN SYNC WITH xbt_thread.c */
876 CRITICAL_SECTION lock;
879 xbt_os_mutex_t xbt_os_mutex_init(void)
881 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
883 /* initialize the critical section object */
884 InitializeCriticalSection(&(res->lock));
889 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
891 EnterCriticalSection(&mutex->lock);
894 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
899 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
902 LeaveCriticalSection(&mutex->lock);
906 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
912 DeleteCriticalSection(&mutex->lock);
916 /***** condition related functions *****/
917 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
923 typedef struct xbt_os_cond_ {
924 /* KEEP IT IN SYNC WITH xbt_thread.c */
925 HANDLE events[MAX_EVENTS];
927 unsigned int waiters_count; /* the number of waiters */
928 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
931 xbt_os_cond_t xbt_os_cond_init(void)
934 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
936 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
938 /* initialize the critical section object */
939 InitializeCriticalSection(&res->waiters_count_lock);
941 res->waiters_count = 0;
943 /* Create an auto-reset event */
944 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
946 if (!res->events[SIGNAL]) {
947 DeleteCriticalSection(&res->waiters_count_lock);
949 THROWF(system_error, 0, "CreateEvent failed for the signals");
952 /* Create a manual-reset event. */
953 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
955 if (!res->events[BROADCAST]) {
957 DeleteCriticalSection(&res->waiters_count_lock);
958 CloseHandle(res->events[SIGNAL]);
960 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
966 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
969 unsigned long wait_result;
972 /* lock the threads counter and increment it */
973 EnterCriticalSection(&cond->waiters_count_lock);
974 cond->waiters_count++;
975 LeaveCriticalSection(&cond->waiters_count_lock);
977 /* unlock the mutex associate with the condition */
978 LeaveCriticalSection(&mutex->lock);
980 /* wait for a signal (broadcast or no) */
981 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
983 if (wait_result == WAIT_FAILED)
984 THROWF(system_error, 0,
985 "WaitForMultipleObjects failed, so we cannot wait on the condition");
987 /* we have a signal lock the condition */
988 EnterCriticalSection(&cond->waiters_count_lock);
989 cond->waiters_count--;
991 /* it's the last waiter or it's a broadcast ? */
992 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
993 && (cond->waiters_count == 0));
995 LeaveCriticalSection(&cond->waiters_count_lock);
997 /* yes it's the last waiter or it's a broadcast
998 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1002 if (!ResetEvent(cond->events[BROADCAST]))
1003 THROWF(system_error, 0, "ResetEvent failed");
1005 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1006 EnterCriticalSection(&mutex->lock);
1009 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1013 unsigned long wait_result = WAIT_TIMEOUT;
1015 unsigned long end = (unsigned long) (delay * 1000);
1019 xbt_os_cond_wait(cond, mutex);
1021 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1022 &(mutex->lock), end);
1024 /* lock the threads counter and increment it */
1025 EnterCriticalSection(&cond->waiters_count_lock);
1026 cond->waiters_count++;
1027 LeaveCriticalSection(&cond->waiters_count_lock);
1029 /* unlock the mutex associate with the condition */
1030 LeaveCriticalSection(&mutex->lock);
1031 /* wait for a signal (broadcast or no) */
1033 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1035 switch (wait_result) {
1037 THROWF(timeout_error, GetLastError(),
1038 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1039 cond, mutex, delay);
1041 THROWF(system_error, GetLastError(),
1042 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1045 /* we have a signal lock the condition */
1046 EnterCriticalSection(&cond->waiters_count_lock);
1047 cond->waiters_count--;
1049 /* it's the last waiter or it's a broadcast ? */
1050 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1051 && (cond->waiters_count == 0));
1053 LeaveCriticalSection(&cond->waiters_count_lock);
1055 /* yes it's the last waiter or it's a broadcast
1056 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1060 if (!ResetEvent(cond->events[BROADCAST]))
1061 THROWF(system_error, 0, "ResetEvent failed");
1063 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1064 EnterCriticalSection(&mutex->lock);
1066 /*THROW_UNIMPLEMENTED; */
1069 void xbt_os_cond_signal(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 if (!SetEvent(cond->events[SIGNAL]))
1079 THROWF(system_error, 0, "SetEvent failed");
1081 xbt_os_thread_yield();
1084 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1088 EnterCriticalSection(&cond->waiters_count_lock);
1089 have_waiters = cond->waiters_count > 0;
1090 LeaveCriticalSection(&cond->waiters_count_lock);
1093 SetEvent(cond->events[BROADCAST]);
1096 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1103 if (!CloseHandle(cond->events[SIGNAL]))
1106 if (!CloseHandle(cond->events[BROADCAST]))
1109 DeleteCriticalSection(&cond->waiters_count_lock);
1114 THROWF(system_error, 0, "Error while destroying the condition");
1117 typedef struct xbt_os_sem_ {
1120 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1124 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1127 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1131 if (value > INT_MAX)
1132 THROWF(arg_error, value,
1133 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1136 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1138 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1139 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1140 strerror(GetLastError()));
1146 InitializeCriticalSection(&(res->value_lock));
1151 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1154 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1157 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1158 THROWF(system_error, GetLastError(),
1159 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1160 EnterCriticalSection(&(sem->value_lock));
1162 LeaveCriticalSection(&(sem->value_lock));
1165 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1169 double end = timeout + xbt_os_time();
1172 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1175 xbt_os_sem_acquire(sem);
1176 } else { /* timeout can be zero <-> try acquire ) */
1179 seconds = (long) floor(end);
1180 milliseconds = (long) ((end - seconds) * 1000);
1181 milliseconds += (seconds * 1000);
1183 switch (WaitForSingleObject(sem->h, milliseconds)) {
1185 EnterCriticalSection(&(sem->value_lock));
1187 LeaveCriticalSection(&(sem->value_lock));
1191 THROWF(timeout_error, GetLastError(),
1192 "semaphore %p wasn't signaled before timeout (%f)", sem,
1197 THROWF(system_error, GetLastError(),
1198 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1199 strerror(GetLastError()));
1204 void xbt_os_sem_release(xbt_os_sem_t sem)
1207 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1209 if (!ReleaseSemaphore(sem->h, 1, NULL))
1210 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1211 strerror(GetLastError()));
1212 EnterCriticalSection(&(sem->value_lock));
1214 LeaveCriticalSection(&(sem->value_lock));
1217 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1220 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1222 if (!CloseHandle(sem->h))
1223 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1224 strerror(GetLastError()));
1226 DeleteCriticalSection(&(sem->value_lock));
1232 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1235 THROWF(arg_error, EINVAL,
1236 "Cannot get the value of the NULL semaphore");
1238 EnterCriticalSection(&(sem->value_lock));
1239 *svalue = sem->value;
1240 LeaveCriticalSection(&(sem->value_lock));
1247 /** @brief Returns the amount of cores on the current host */
1248 int xbt_os_get_numcores(void) {
1250 SYSTEM_INFO sysinfo;
1251 GetSystemInfo(&sysinfo);
1252 return sysinfo.dwNumberOfProcessors;
1258 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1259 sysctl(nm, 2, &count, &len, NULL, 0);
1263 sysctl(nm, 2, &count, &len, NULL, 0);
1264 if(count < 1) { count = 1; }
1268 return sysconf(_SC_NPROCESSORS_ONLN);
1273 /***** reentrant mutexes *****/
1274 typedef struct xbt_os_rmutex_ {
1275 xbt_os_mutex_t mutex;
1276 xbt_os_thread_t owner;
1278 } s_xbt_os_rmutex_t;
1280 void xbt_os_thread_set_extra_data(void *data)
1282 xbt_os_thread_self()->extra_data = data;
1285 void *xbt_os_thread_get_extra_data(void)
1287 xbt_os_thread_t self = xbt_os_thread_self();
1288 return self? self->extra_data : NULL;
1291 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1293 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1294 rmutex->mutex = xbt_os_mutex_init();
1295 rmutex->owner = NULL;
1300 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1302 xbt_os_thread_t self = xbt_os_thread_self();
1305 /* the thread module is not initialized yet */
1306 rmutex->owner = NULL;
1310 if (self != rmutex->owner) {
1311 xbt_os_mutex_acquire(rmutex->mutex);
1312 rmutex->owner = self;
1319 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1321 if (rmutex->owner == NULL) {
1322 /* the thread module was not initialized */
1326 xbt_assert(rmutex->owner == xbt_os_thread_self());
1328 if (--rmutex->count == 0) {
1329 rmutex->owner = NULL;
1330 xbt_os_mutex_release(rmutex->mutex);
1334 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1336 xbt_os_mutex_destroy(rmutex->mutex);