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 const char *xbt_os_thread_name(xbt_os_thread_t t)
238 const char *xbt_os_thread_self_name(void)
240 xbt_os_thread_t me = xbt_os_thread_self();
241 return me ? me->name : "main";
244 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
249 if ((errcode = pthread_join(thread->t, thread_return)))
250 THROWF(system_error, errcode, "pthread_join failed: %s",
252 xbt_os_thread_free_thread_data(thread);
255 void xbt_os_thread_exit(int *retval)
257 pthread_exit(retval);
260 xbt_os_thread_t xbt_os_thread_self(void)
264 if (!thread_mod_inited)
267 res = pthread_getspecific(xbt_self_thread_key);
272 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
275 if ((errcode = pthread_key_create(key, NULL)))
276 THROWF(system_error, errcode, "pthread_key_create failed");
279 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
282 if ((errcode = pthread_setspecific(key, value)))
283 THROWF(system_error, errcode, "pthread_setspecific failed");
286 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
287 return pthread_getspecific(key);
290 void xbt_os_thread_detach(xbt_os_thread_t thread)
292 thread->detached = 1;
293 pthread_detach(thread->t);
297 void xbt_os_thread_yield(void)
302 void xbt_os_thread_cancel(xbt_os_thread_t t)
304 pthread_cancel(t->t);
307 /****** mutex related functions ******/
308 typedef struct xbt_os_mutex_ {
309 /* KEEP IT IN SYNC WITH xbt_thread.c */
316 xbt_os_mutex_t xbt_os_mutex_init(void)
318 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
321 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
322 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
328 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
332 if ((errcode = pthread_mutex_lock(&(mutex->m))))
333 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
334 mutex, strerror(errcode));
338 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
343 xbt_os_mutex_acquire(mutex);
345 } else if (delay == 0) {
346 errcode = pthread_mutex_trylock(&(mutex->m));
352 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
354 THROWF(system_error, errcode,
355 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
362 #ifdef HAVE_MUTEX_TIMEDLOCK
363 struct timespec ts_end;
364 double end = delay + xbt_os_time();
366 ts_end.tv_sec = (time_t) floor(end);
367 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
368 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
370 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
372 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
373 double start = xbt_os_time();
375 errcode = pthread_mutex_trylock(&(mutex->m));
376 if (errcode == EBUSY)
377 xbt_os_thread_yield();
378 } while (errcode == EBUSY && xbt_os_time() - start < delay);
380 if (errcode == EBUSY)
383 #endif /* HAVE_MUTEX_TIMEDLOCK */
390 THROWF(timeout_error, delay,
391 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
394 THROWF(system_error, errcode,
395 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
401 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
405 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
406 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
407 mutex, strerror(errcode));
410 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
417 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
418 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
419 mutex, strerror(errcode));
423 /***** condition related functions *****/
424 typedef struct xbt_os_cond_ {
425 /* KEEP IT IN SYNC WITH xbt_thread.c */
429 xbt_os_cond_t xbt_os_cond_init(void)
431 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
433 if ((errcode = pthread_cond_init(&(res->c), NULL)))
434 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
440 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
443 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
444 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
445 cond, mutex, strerror(errcode));
449 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
453 struct timespec ts_end;
454 double end = delay + xbt_os_time();
457 xbt_os_cond_wait(cond, mutex);
459 ts_end.tv_sec = (time_t) floor(end);
460 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
461 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
464 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
468 THROWF(timeout_error, errcode,
469 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
472 THROWF(system_error, errcode,
473 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
474 delay, strerror(errcode));
479 void xbt_os_cond_signal(xbt_os_cond_t cond)
482 if ((errcode = pthread_cond_signal(&(cond->c))))
483 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
484 cond, strerror(errcode));
487 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
490 if ((errcode = pthread_cond_broadcast(&(cond->c))))
491 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
492 cond, strerror(errcode));
495 void xbt_os_cond_destroy(xbt_os_cond_t cond)
502 if ((errcode = pthread_cond_destroy(&(cond->c))))
503 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
504 cond, strerror(errcode));
508 void *xbt_os_thread_getparam(void)
510 xbt_os_thread_t t = xbt_os_thread_self();
511 return t ? t->param : NULL;
514 typedef struct xbt_os_sem_ {
515 #ifndef HAVE_SEM_INIT
523 #define SEM_FAILED (-1)
526 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
528 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
530 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
531 * Any attempt to use it leads to ENOSYS (function not implemented).
532 * If such a prehistoric system is detected, do the job with sem_open instead
535 if (sem_init(&(res->s), 0, value) != 0)
536 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
539 #else /* damn, no sem_init(). Reimplement it */
541 xbt_os_mutex_acquire(next_sem_ID_lock);
542 res->name = bprintf("/%d", ++next_sem_ID);
543 xbt_os_mutex_release(next_sem_ID_lock);
545 res->ps = sem_open(res->name, O_CREAT, 0644, value);
546 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
547 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
548 res->name[13] = '\0';
549 res->ps = sem_open(res->name, O_CREAT, 0644, value);
551 if ((res->ps == (sem_t *) SEM_FAILED))
552 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
554 /* Remove the name from the semaphore namespace: we never join on it */
555 if (sem_unlink(res->name) < 0)
556 THROWF(system_error, errno, "sem_unlink() failed: %s",
564 void xbt_os_sem_acquire(xbt_os_sem_t sem)
567 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
568 if (sem_wait(sem->ps) < 0)
569 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
572 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
577 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
580 xbt_os_sem_acquire(sem);
581 } else if (delay == 0) {
582 errcode = sem_trywait(sem->ps);
588 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
590 THROWF(system_error, errcode,
591 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
597 struct timespec ts_end;
598 double end = delay + xbt_os_time();
600 ts_end.tv_sec = (time_t) floor(end);
601 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
602 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
603 errcode = sem_timedwait(sem->s, &ts_end);
605 #else /* Okay, reimplement this function then */
606 double start = xbt_os_time();
608 errcode = sem_trywait(sem->ps);
609 if (errcode == EBUSY)
610 xbt_os_thread_yield();
611 } while (errcode == EBUSY && xbt_os_time() - start < delay);
613 if (errcode == EBUSY)
622 THROWF(timeout_error, delay,
623 "semaphore %p wasn't signaled before timeout (%f)", sem,
627 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
628 delay, strerror(errcode));
633 void xbt_os_sem_release(xbt_os_sem_t sem)
636 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
638 if (sem_post(sem->ps) < 0)
639 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
642 void xbt_os_sem_destroy(xbt_os_sem_t sem)
645 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
648 if (sem_destroy(sem->ps) < 0)
649 THROWF(system_error, errno, "sem_destroy() failed: %s",
652 if (sem_close(sem->ps) < 0)
653 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
660 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
663 THROWF(arg_error, EINVAL,
664 "Cannot get the value of the NULL semaphore");
666 if (sem_getvalue(&(sem->s), svalue) < 0)
667 THROWF(system_error, errno, "sem_getvalue() failed: %s",
671 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
673 #elif defined(_XBT_WIN32)
677 typedef struct xbt_os_thread_ {
679 HANDLE handle; /* the win thread handle */
680 unsigned long id; /* the win thread id */
681 pvoid_f_pvoid_t start_routine;
686 /* so we can specify the size of the stack of the threads */
687 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
688 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
691 /* the default size of the stack of the threads (in bytes)*/
692 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
693 static int stack_size=0;
694 /* key to the TLS containing the xbt_os_thread_t structure */
695 static unsigned long xbt_self_thread_key;
697 void xbt_os_thread_mod_preinit(void)
699 xbt_self_thread_key = TlsAlloc();
702 void xbt_os_thread_mod_postexit(void)
705 if (!TlsFree(xbt_self_thread_key))
706 THROWF(system_error, (int) GetLastError(),
707 "TlsFree() failed to cleanup the thread submodule");
710 int xbt_os_thread_atfork(void (*prepare)(void),
711 void (*parent)(void), void (*child)(void))
716 static DWORD WINAPI wrapper_start_routine(void *s)
718 xbt_os_thread_t t = (xbt_os_thread_t) s;
721 if (!TlsSetValue(xbt_self_thread_key, t))
722 THROWF(system_error, (int) GetLastError(),
723 "TlsSetValue of data describing the created thread failed");
725 rv = (DWORD *) ((t->start_routine) (t->param));
732 xbt_os_thread_t xbt_os_thread_create(const char *name,
733 pvoid_f_pvoid_t start_routine,
738 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
740 t->name = xbt_strdup(name);
741 t->start_routine = start_routine;
743 t->extra_data = extra_data;
744 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
745 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
746 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
750 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
756 void xbt_os_thread_setstacksize(int size)
761 const char *xbt_os_thread_name(xbt_os_thread_t t)
766 const char *xbt_os_thread_self_name(void)
768 xbt_os_thread_t t = xbt_os_thread_self();
769 return t ? t->name : "main";
772 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
775 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
776 THROWF(system_error, (int) GetLastError(),
777 "WaitForSingleObject failed");
781 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
782 THROWF(system_error, (int) GetLastError(),
783 "GetExitCodeThread failed");
786 CloseHandle(thread->handle);
793 void xbt_os_thread_exit(int *retval)
801 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
806 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
808 if (!TlsSetValue(key, value))
809 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
812 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
813 return TlsGetValue(key);
816 void xbt_os_thread_detach(xbt_os_thread_t thread)
822 xbt_os_thread_t xbt_os_thread_self(void)
824 return TlsGetValue(xbt_self_thread_key);
827 void *xbt_os_thread_getparam(void)
829 xbt_os_thread_t t = xbt_os_thread_self();
834 void xbt_os_thread_yield(void)
839 void xbt_os_thread_cancel(xbt_os_thread_t t)
841 if (!TerminateThread(t->handle, 0))
842 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
845 /****** mutex related functions ******/
846 typedef struct xbt_os_mutex_ {
847 /* KEEP IT IN SYNC WITH xbt_thread.c */
848 CRITICAL_SECTION lock;
851 xbt_os_mutex_t xbt_os_mutex_init(void)
853 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
855 /* initialize the critical section object */
856 InitializeCriticalSection(&(res->lock));
861 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
863 EnterCriticalSection(&mutex->lock);
866 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
871 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
874 LeaveCriticalSection(&mutex->lock);
878 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
884 DeleteCriticalSection(&mutex->lock);
888 /***** condition related functions *****/
889 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
895 typedef struct xbt_os_cond_ {
896 /* KEEP IT IN SYNC WITH xbt_thread.c */
897 HANDLE events[MAX_EVENTS];
899 unsigned int waiters_count; /* the number of waiters */
900 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
903 xbt_os_cond_t xbt_os_cond_init(void)
906 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
908 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
910 /* initialize the critical section object */
911 InitializeCriticalSection(&res->waiters_count_lock);
913 res->waiters_count = 0;
915 /* Create an auto-reset event */
916 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
918 if (!res->events[SIGNAL]) {
919 DeleteCriticalSection(&res->waiters_count_lock);
921 THROWF(system_error, 0, "CreateEvent failed for the signals");
924 /* Create a manual-reset event. */
925 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
927 if (!res->events[BROADCAST]) {
929 DeleteCriticalSection(&res->waiters_count_lock);
930 CloseHandle(res->events[SIGNAL]);
932 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
938 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
941 unsigned long wait_result;
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);
952 /* wait for a signal (broadcast or no) */
953 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
955 if (wait_result == WAIT_FAILED)
956 THROWF(system_error, 0,
957 "WaitForMultipleObjects failed, so we cannot wait on the condition");
959 /* we have a signal lock the condition */
960 EnterCriticalSection(&cond->waiters_count_lock);
961 cond->waiters_count--;
963 /* it's the last waiter or it's a broadcast ? */
964 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
965 && (cond->waiters_count == 0));
967 LeaveCriticalSection(&cond->waiters_count_lock);
969 /* yes it's the last waiter or it's a broadcast
970 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
974 if (!ResetEvent(cond->events[BROADCAST]))
975 THROWF(system_error, 0, "ResetEvent failed");
977 /* relock the mutex associated with the condition in accordance with the posix thread specification */
978 EnterCriticalSection(&mutex->lock);
981 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
985 unsigned long wait_result = WAIT_TIMEOUT;
987 unsigned long end = (unsigned long) (delay * 1000);
991 xbt_os_cond_wait(cond, mutex);
993 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
994 &(mutex->lock), end);
996 /* lock the threads counter and increment it */
997 EnterCriticalSection(&cond->waiters_count_lock);
998 cond->waiters_count++;
999 LeaveCriticalSection(&cond->waiters_count_lock);
1001 /* unlock the mutex associate with the condition */
1002 LeaveCriticalSection(&mutex->lock);
1003 /* wait for a signal (broadcast or no) */
1005 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1007 switch (wait_result) {
1009 THROWF(timeout_error, GetLastError(),
1010 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1011 cond, mutex, delay);
1013 THROWF(system_error, GetLastError(),
1014 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1017 /* we have a signal lock the condition */
1018 EnterCriticalSection(&cond->waiters_count_lock);
1019 cond->waiters_count--;
1021 /* it's the last waiter or it's a broadcast ? */
1022 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1023 && (cond->waiters_count == 0));
1025 LeaveCriticalSection(&cond->waiters_count_lock);
1027 /* yes it's the last waiter or it's a broadcast
1028 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1032 if (!ResetEvent(cond->events[BROADCAST]))
1033 THROWF(system_error, 0, "ResetEvent failed");
1035 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1036 EnterCriticalSection(&mutex->lock);
1038 /*THROW_UNIMPLEMENTED; */
1041 void xbt_os_cond_signal(xbt_os_cond_t cond)
1045 EnterCriticalSection(&cond->waiters_count_lock);
1046 have_waiters = cond->waiters_count > 0;
1047 LeaveCriticalSection(&cond->waiters_count_lock);
1050 if (!SetEvent(cond->events[SIGNAL]))
1051 THROWF(system_error, 0, "SetEvent failed");
1053 xbt_os_thread_yield();
1056 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1060 EnterCriticalSection(&cond->waiters_count_lock);
1061 have_waiters = cond->waiters_count > 0;
1062 LeaveCriticalSection(&cond->waiters_count_lock);
1065 SetEvent(cond->events[BROADCAST]);
1068 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1075 if (!CloseHandle(cond->events[SIGNAL]))
1078 if (!CloseHandle(cond->events[BROADCAST]))
1081 DeleteCriticalSection(&cond->waiters_count_lock);
1086 THROWF(system_error, 0, "Error while destroying the condition");
1089 typedef struct xbt_os_sem_ {
1092 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1096 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1099 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1103 if (value > INT_MAX)
1104 THROWF(arg_error, value,
1105 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1108 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1110 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1111 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1112 strerror(GetLastError()));
1118 InitializeCriticalSection(&(res->value_lock));
1123 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1126 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1129 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1130 THROWF(system_error, GetLastError(),
1131 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1132 EnterCriticalSection(&(sem->value_lock));
1134 LeaveCriticalSection(&(sem->value_lock));
1137 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1141 double end = timeout + xbt_os_time();
1144 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1147 xbt_os_sem_acquire(sem);
1148 } else { /* timeout can be zero <-> try acquire ) */
1151 seconds = (long) floor(end);
1152 milliseconds = (long) ((end - seconds) * 1000);
1153 milliseconds += (seconds * 1000);
1155 switch (WaitForSingleObject(sem->h, milliseconds)) {
1157 EnterCriticalSection(&(sem->value_lock));
1159 LeaveCriticalSection(&(sem->value_lock));
1163 THROWF(timeout_error, GetLastError(),
1164 "semaphore %p wasn't signaled before timeout (%f)", sem,
1169 THROWF(system_error, GetLastError(),
1170 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1171 strerror(GetLastError()));
1176 void xbt_os_sem_release(xbt_os_sem_t sem)
1179 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1181 if (!ReleaseSemaphore(sem->h, 1, NULL))
1182 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1183 strerror(GetLastError()));
1184 EnterCriticalSection(&(sem->value_lock));
1186 LeaveCriticalSection(&(sem->value_lock));
1189 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1192 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1194 if (!CloseHandle(sem->h))
1195 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1196 strerror(GetLastError()));
1198 DeleteCriticalSection(&(sem->value_lock));
1204 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1207 THROWF(arg_error, EINVAL,
1208 "Cannot get the value of the NULL semaphore");
1210 EnterCriticalSection(&(sem->value_lock));
1211 *svalue = sem->value;
1212 LeaveCriticalSection(&(sem->value_lock));
1219 /** @brief Returns the amount of cores on the current host */
1220 int xbt_os_get_numcores(void) {
1222 SYSTEM_INFO sysinfo;
1223 GetSystemInfo(&sysinfo);
1224 return sysinfo.dwNumberOfProcessors;
1230 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1231 sysctl(nm, 2, &count, &len, NULL, 0);
1235 sysctl(nm, 2, &count, &len, NULL, 0);
1236 if(count < 1) { count = 1; }
1240 return sysconf(_SC_NPROCESSORS_ONLN);
1245 /***** reentrant mutexes *****/
1246 typedef struct xbt_os_rmutex_ {
1247 xbt_os_mutex_t mutex;
1248 xbt_os_thread_t owner;
1250 } s_xbt_os_rmutex_t;
1252 void xbt_os_thread_set_extra_data(void *data)
1254 xbt_os_thread_self()->extra_data = data;
1257 void *xbt_os_thread_get_extra_data(void)
1259 xbt_os_thread_t self = xbt_os_thread_self();
1260 return self? self->extra_data : NULL;
1263 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1265 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1266 rmutex->mutex = xbt_os_mutex_init();
1267 rmutex->owner = NULL;
1272 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1274 xbt_os_thread_t self = xbt_os_thread_self();
1277 /* the thread module is not initialized yet */
1278 rmutex->owner = NULL;
1282 if (self != rmutex->owner) {
1283 xbt_os_mutex_acquire(rmutex->mutex);
1284 rmutex->owner = self;
1291 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1293 if (rmutex->owner == NULL) {
1294 /* the thread module was not initialized */
1298 xbt_assert(rmutex->owner == xbt_os_thread_self());
1300 if (--rmutex->count == 0) {
1301 rmutex->owner = NULL;
1302 xbt_os_mutex_release(rmutex->mutex);
1306 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1308 xbt_os_mutex_destroy(rmutex->mutex);