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. */
12 #elif defined(__MACH__) && defined(__APPLE__)
14 #include <sys/types.h>
15 #include <sys/sysctl.h>
20 #include "internal_config.h"
21 #include "xbt/sysdep.h"
23 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
25 #include "xbt/xbt_os_time.h" /* Portable time facilities */
26 #include "xbt/xbt_os_thread.h" /* This module */
27 #include "xbt_modinter.h" /* Initialization/finalization of this module */
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
30 "Synchronization mechanism (OS-level)");
32 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
37 #include <semaphore.h>
44 /* use named sempahore when sem_init() does not work */
46 static int next_sem_ID = 0;
47 static xbt_os_mutex_t next_sem_ID_lock;
50 typedef struct xbt_os_thread_ {
55 pvoid_f_pvoid_t start_routine;
56 xbt_running_ctx_t *running_ctx;
59 static xbt_os_thread_t main_thread = NULL;
61 /* thread-specific data containing the xbt_os_thread_t structure */
62 static pthread_key_t xbt_self_thread_key;
63 static int thread_mod_inited = 0;
65 /* defaults attribute for pthreads */
66 //FIXME: find where to put this
67 static pthread_attr_t thread_attr;
69 /* frees the xbt_os_thread_t corresponding to the current thread */
70 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
72 if (thread == main_thread) /* just killed main thread */
75 free(thread->running_ctx);
80 /* callback: context fetching */
81 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
83 return xbt_os_thread_self()->running_ctx;
86 /* callback: termination */
87 static void _os_thread_ex_terminate(xbt_ex_t * e)
91 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
94 void xbt_os_thread_mod_preinit(void)
98 if (thread_mod_inited)
101 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
102 THROWF(system_error, errcode,
103 "pthread_key_create failed for xbt_self_thread_key");
105 main_thread = xbt_new(s_xbt_os_thread_t, 1);
106 main_thread->name = (char *) "main";
107 main_thread->start_routine = NULL;
108 main_thread->param = NULL;
109 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
110 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
112 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
113 THROWF(system_error, errcode,
114 "pthread_setspecific failed for xbt_self_thread_key");
116 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
117 __xbt_ex_terminate = _os_thread_ex_terminate;
119 pthread_attr_init(&thread_attr);
121 thread_mod_inited = 1;
123 #ifndef HAVE_SEM_INIT
124 next_sem_ID_lock = xbt_os_mutex_init();
129 void xbt_os_thread_mod_postexit(void)
131 /* FIXME: don't try to free our key on shutdown.
132 Valgrind detects no leak if we don't, and whine if we try to */
135 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
136 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
137 free(main_thread->running_ctx);
140 thread_mod_inited = 0;
141 #ifndef HAVE_SEM_INIT
142 xbt_os_mutex_destroy(next_sem_ID_lock);
145 /* Restore the default exception setup */
146 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
147 __xbt_ex_terminate = &__xbt_ex_terminate_default;
150 /* this function is critical to tesh+mmalloc, don't mess with it */
151 int xbt_os_thread_atfork(void (*prepare)(void),
152 void (*parent)(void), void (*child)(void))
155 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
157 return pthread_atfork(prepare, parent, child);
161 static void *wrapper_start_routine(void *s)
163 xbt_os_thread_t t = s;
166 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
167 THROWF(system_error, errcode,
168 "pthread_setspecific failed for xbt_self_thread_key");
170 void *res = t->start_routine(t->param);
172 xbt_os_thread_free_thread_data(t);
177 xbt_os_thread_t xbt_os_thread_create(const char *name,
178 pvoid_f_pvoid_t start_routine,
184 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
185 res_thread->detached = 0;
186 res_thread->name = xbt_strdup(name);
187 res_thread->start_routine = start_routine;
188 res_thread->param = param;
189 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
190 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
191 res_thread->extra_data = extra_data;
193 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
194 wrapper_start_routine, res_thread)))
195 THROWF(system_error, errcode,
196 "pthread_create failed: %s", strerror(errcode));
205 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
206 pthread_t pthread = thread->t;
210 CPU_SET(cpu, &cpuset);
211 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
216 void xbt_os_thread_setstacksize(int stack_size)
218 size_t alignment[] = {
220 #ifdef PTHREAD_STACK_MIN
230 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
233 res = pthread_attr_setstacksize(&thread_attr, sz);
235 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
236 /* Invalid size, try again with next multiple of alignment[i]. */
237 size_t rem = sz % alignment[i];
238 if (rem != 0 || sz == 0) {
239 size_t sz2 = sz - rem + alignment[i];
240 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
243 res = pthread_attr_setstacksize(&thread_attr, sz);
248 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
250 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
253 void xbt_os_thread_setguardsize(int guard_size)
256 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
258 size_t sz = guard_size;
259 int res = pthread_attr_setguardsize(&thread_attr, sz);
261 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
265 const char *xbt_os_thread_name(xbt_os_thread_t t)
270 const char *xbt_os_thread_self_name(void)
272 xbt_os_thread_t me = xbt_os_thread_self();
273 return me ? me->name : "main";
276 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
281 if ((errcode = pthread_join(thread->t, thread_return)))
282 THROWF(system_error, errcode, "pthread_join failed: %s",
284 xbt_os_thread_free_thread_data(thread);
287 void xbt_os_thread_exit(int *retval)
289 pthread_exit(retval);
292 xbt_os_thread_t xbt_os_thread_self(void)
296 if (!thread_mod_inited)
299 res = pthread_getspecific(xbt_self_thread_key);
304 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
307 if ((errcode = pthread_key_create(key, NULL)))
308 THROWF(system_error, errcode, "pthread_key_create failed");
311 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
314 if ((errcode = pthread_setspecific(key, value)))
315 THROWF(system_error, errcode, "pthread_setspecific failed");
318 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
319 return pthread_getspecific(key);
322 void xbt_os_thread_detach(xbt_os_thread_t thread)
324 thread->detached = 1;
325 pthread_detach(thread->t);
329 void xbt_os_thread_yield(void)
334 void xbt_os_thread_cancel(xbt_os_thread_t t)
336 pthread_cancel(t->t);
339 /****** mutex related functions ******/
340 typedef struct xbt_os_mutex_ {
341 /* KEEP IT IN SYNC WITH xbt_thread.c */
348 xbt_os_mutex_t xbt_os_mutex_init(void)
350 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
353 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
354 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
360 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
364 if ((errcode = pthread_mutex_lock(&(mutex->m))))
365 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
366 mutex, strerror(errcode));
370 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
375 xbt_os_mutex_acquire(mutex);
377 } else if (delay == 0) {
378 errcode = pthread_mutex_trylock(&(mutex->m));
384 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
386 THROWF(system_error, errcode,
387 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
394 #ifdef HAVE_MUTEX_TIMEDLOCK
395 struct timespec ts_end;
396 double end = delay + xbt_os_time();
398 ts_end.tv_sec = (time_t) floor(end);
399 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
400 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
402 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
404 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
405 double start = xbt_os_time();
407 errcode = pthread_mutex_trylock(&(mutex->m));
408 if (errcode == EBUSY)
409 xbt_os_thread_yield();
410 } while (errcode == EBUSY && xbt_os_time() - start < delay);
412 if (errcode == EBUSY)
415 #endif /* HAVE_MUTEX_TIMEDLOCK */
422 THROWF(timeout_error, delay,
423 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
426 THROWF(system_error, errcode,
427 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
433 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
437 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
438 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
439 mutex, strerror(errcode));
442 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
449 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
450 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
451 mutex, strerror(errcode));
455 /***** condition related functions *****/
456 typedef struct xbt_os_cond_ {
457 /* KEEP IT IN SYNC WITH xbt_thread.c */
461 xbt_os_cond_t xbt_os_cond_init(void)
463 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
465 if ((errcode = pthread_cond_init(&(res->c), NULL)))
466 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
472 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
475 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
476 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
477 cond, mutex, strerror(errcode));
481 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
485 struct timespec ts_end;
486 double end = delay + xbt_os_time();
489 xbt_os_cond_wait(cond, mutex);
491 ts_end.tv_sec = (time_t) floor(end);
492 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
493 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
496 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
500 THROWF(timeout_error, errcode,
501 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
504 THROWF(system_error, errcode,
505 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
506 delay, strerror(errcode));
511 void xbt_os_cond_signal(xbt_os_cond_t cond)
514 if ((errcode = pthread_cond_signal(&(cond->c))))
515 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
516 cond, strerror(errcode));
519 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
522 if ((errcode = pthread_cond_broadcast(&(cond->c))))
523 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
524 cond, strerror(errcode));
527 void xbt_os_cond_destroy(xbt_os_cond_t cond)
534 if ((errcode = pthread_cond_destroy(&(cond->c))))
535 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
536 cond, strerror(errcode));
540 void *xbt_os_thread_getparam(void)
542 xbt_os_thread_t t = xbt_os_thread_self();
543 return t ? t->param : NULL;
546 typedef struct xbt_os_sem_ {
547 #ifndef HAVE_SEM_INIT
555 #define SEM_FAILED (-1)
558 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
560 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
562 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
563 * Any attempt to use it leads to ENOSYS (function not implemented).
564 * If such a prehistoric system is detected, do the job with sem_open instead
567 if (sem_init(&(res->s), 0, value) != 0)
568 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
571 #else /* damn, no sem_init(). Reimplement it */
573 xbt_os_mutex_acquire(next_sem_ID_lock);
574 res->name = bprintf("/%d", ++next_sem_ID);
575 xbt_os_mutex_release(next_sem_ID_lock);
577 res->ps = sem_open(res->name, O_CREAT, 0644, value);
578 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
579 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
580 res->name[13] = '\0';
581 res->ps = sem_open(res->name, O_CREAT, 0644, value);
583 if (res->ps == (sem_t *) SEM_FAILED)
584 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
586 /* Remove the name from the semaphore namespace: we never join on it */
587 if (sem_unlink(res->name) < 0)
588 THROWF(system_error, errno, "sem_unlink() failed: %s",
596 void xbt_os_sem_acquire(xbt_os_sem_t sem)
599 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
600 if (sem_wait(sem->ps) < 0)
601 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
604 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
609 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
612 xbt_os_sem_acquire(sem);
613 } else if (delay == 0) {
614 errcode = sem_trywait(sem->ps);
620 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
622 THROWF(system_error, errcode,
623 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
629 struct timespec ts_end;
630 double end = delay + xbt_os_time();
632 ts_end.tv_sec = (time_t) floor(end);
633 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
634 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
635 errcode = sem_timedwait(sem->s, &ts_end);
637 #else /* Okay, reimplement this function then */
638 double start = xbt_os_time();
640 errcode = sem_trywait(sem->ps);
641 if (errcode == EBUSY)
642 xbt_os_thread_yield();
643 } while (errcode == EBUSY && xbt_os_time() - start < delay);
645 if (errcode == EBUSY)
654 THROWF(timeout_error, delay,
655 "semaphore %p wasn't signaled before timeout (%f)", sem,
659 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
660 delay, strerror(errcode));
665 void xbt_os_sem_release(xbt_os_sem_t sem)
668 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
670 if (sem_post(sem->ps) < 0)
671 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
674 void xbt_os_sem_destroy(xbt_os_sem_t sem)
677 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
680 if (sem_destroy(sem->ps) < 0)
681 THROWF(system_error, errno, "sem_destroy() failed: %s",
684 if (sem_close(sem->ps) < 0)
685 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
692 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
695 THROWF(arg_error, EINVAL,
696 "Cannot get the value of the NULL semaphore");
698 if (sem_getvalue(&(sem->s), svalue) < 0)
699 THROWF(system_error, errno, "sem_getvalue() failed: %s",
703 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
705 #elif defined(_XBT_WIN32)
709 typedef struct xbt_os_thread_ {
711 HANDLE handle; /* the win thread handle */
712 unsigned long id; /* the win thread id */
713 pvoid_f_pvoid_t start_routine;
718 /* so we can specify the size of the stack of the threads */
719 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
720 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
723 /* the default size of the stack of the threads (in bytes)*/
724 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
725 static int stack_size=0;
726 /* key to the TLS containing the xbt_os_thread_t structure */
727 static unsigned long xbt_self_thread_key;
729 void xbt_os_thread_mod_preinit(void)
731 xbt_self_thread_key = TlsAlloc();
734 void xbt_os_thread_mod_postexit(void)
737 if (!TlsFree(xbt_self_thread_key))
738 THROWF(system_error, (int) GetLastError(),
739 "TlsFree() failed to cleanup the thread submodule");
742 int xbt_os_thread_atfork(void (*prepare)(void),
743 void (*parent)(void), void (*child)(void))
748 static DWORD WINAPI wrapper_start_routine(void *s)
750 xbt_os_thread_t t = (xbt_os_thread_t) s;
753 if (!TlsSetValue(xbt_self_thread_key, t))
754 THROWF(system_error, (int) GetLastError(),
755 "TlsSetValue of data describing the created thread failed");
757 rv = (DWORD *) ((t->start_routine) (t->param));
764 xbt_os_thread_t xbt_os_thread_create(const char *name,
765 pvoid_f_pvoid_t start_routine,
770 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
772 t->name = xbt_strdup(name);
773 t->start_routine = start_routine;
775 t->extra_data = extra_data;
776 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
777 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
778 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
782 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
788 void xbt_os_thread_setstacksize(int size)
793 void xbt_os_thread_setguardsize(int size)
795 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
798 const char *xbt_os_thread_name(xbt_os_thread_t t)
803 const char *xbt_os_thread_self_name(void)
805 xbt_os_thread_t t = xbt_os_thread_self();
806 return t ? t->name : "main";
809 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
812 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
813 THROWF(system_error, (int) GetLastError(),
814 "WaitForSingleObject failed");
818 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
819 THROWF(system_error, (int) GetLastError(),
820 "GetExitCodeThread failed");
823 CloseHandle(thread->handle);
830 void xbt_os_thread_exit(int *retval)
838 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
843 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
845 if (!TlsSetValue(key, value))
846 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
849 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
850 return TlsGetValue(key);
853 void xbt_os_thread_detach(xbt_os_thread_t thread)
859 xbt_os_thread_t xbt_os_thread_self(void)
861 return TlsGetValue(xbt_self_thread_key);
864 void *xbt_os_thread_getparam(void)
866 xbt_os_thread_t t = xbt_os_thread_self();
871 void xbt_os_thread_yield(void)
876 void xbt_os_thread_cancel(xbt_os_thread_t t)
878 if (!TerminateThread(t->handle, 0))
879 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
882 /****** mutex related functions ******/
883 typedef struct xbt_os_mutex_ {
884 /* KEEP IT IN SYNC WITH xbt_thread.c */
885 CRITICAL_SECTION lock;
888 xbt_os_mutex_t xbt_os_mutex_init(void)
890 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
892 /* initialize the critical section object */
893 InitializeCriticalSection(&(res->lock));
898 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
900 EnterCriticalSection(&mutex->lock);
903 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
908 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
911 LeaveCriticalSection(&mutex->lock);
915 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
921 DeleteCriticalSection(&mutex->lock);
925 /***** condition related functions *****/
926 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
932 typedef struct xbt_os_cond_ {
933 /* KEEP IT IN SYNC WITH xbt_thread.c */
934 HANDLE events[MAX_EVENTS];
936 unsigned int waiters_count; /* the number of waiters */
937 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
940 xbt_os_cond_t xbt_os_cond_init(void)
943 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
945 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
947 /* initialize the critical section object */
948 InitializeCriticalSection(&res->waiters_count_lock);
950 res->waiters_count = 0;
952 /* Create an auto-reset event */
953 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
955 if (!res->events[SIGNAL]) {
956 DeleteCriticalSection(&res->waiters_count_lock);
958 THROWF(system_error, 0, "CreateEvent failed for the signals");
961 /* Create a manual-reset event. */
962 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
964 if (!res->events[BROADCAST]) {
966 DeleteCriticalSection(&res->waiters_count_lock);
967 CloseHandle(res->events[SIGNAL]);
969 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
975 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
978 unsigned long wait_result;
981 /* lock the threads counter and increment it */
982 EnterCriticalSection(&cond->waiters_count_lock);
983 cond->waiters_count++;
984 LeaveCriticalSection(&cond->waiters_count_lock);
986 /* unlock the mutex associate with the condition */
987 LeaveCriticalSection(&mutex->lock);
989 /* wait for a signal (broadcast or no) */
990 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
992 if (wait_result == WAIT_FAILED)
993 THROWF(system_error, 0,
994 "WaitForMultipleObjects failed, so we cannot wait on the condition");
996 /* we have a signal lock the condition */
997 EnterCriticalSection(&cond->waiters_count_lock);
998 cond->waiters_count--;
1000 /* it's the last waiter or it's a broadcast ? */
1001 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1002 && (cond->waiters_count == 0));
1004 LeaveCriticalSection(&cond->waiters_count_lock);
1006 /* yes it's the last waiter or it's a broadcast
1007 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1011 if (!ResetEvent(cond->events[BROADCAST]))
1012 THROWF(system_error, 0, "ResetEvent failed");
1014 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1015 EnterCriticalSection(&mutex->lock);
1018 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1022 unsigned long wait_result = WAIT_TIMEOUT;
1024 unsigned long end = (unsigned long) (delay * 1000);
1028 xbt_os_cond_wait(cond, mutex);
1030 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1031 &(mutex->lock), end);
1033 /* lock the threads counter and increment it */
1034 EnterCriticalSection(&cond->waiters_count_lock);
1035 cond->waiters_count++;
1036 LeaveCriticalSection(&cond->waiters_count_lock);
1038 /* unlock the mutex associate with the condition */
1039 LeaveCriticalSection(&mutex->lock);
1040 /* wait for a signal (broadcast or no) */
1042 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1044 switch (wait_result) {
1046 THROWF(timeout_error, GetLastError(),
1047 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1048 cond, mutex, delay);
1050 THROWF(system_error, GetLastError(),
1051 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1054 /* we have a signal lock the condition */
1055 EnterCriticalSection(&cond->waiters_count_lock);
1056 cond->waiters_count--;
1058 /* it's the last waiter or it's a broadcast ? */
1059 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1060 && (cond->waiters_count == 0));
1062 LeaveCriticalSection(&cond->waiters_count_lock);
1064 /* yes it's the last waiter or it's a broadcast
1065 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1069 if (!ResetEvent(cond->events[BROADCAST]))
1070 THROWF(system_error, 0, "ResetEvent failed");
1072 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1073 EnterCriticalSection(&mutex->lock);
1075 /*THROW_UNIMPLEMENTED; */
1078 void xbt_os_cond_signal(xbt_os_cond_t cond)
1082 EnterCriticalSection(&cond->waiters_count_lock);
1083 have_waiters = cond->waiters_count > 0;
1084 LeaveCriticalSection(&cond->waiters_count_lock);
1087 if (!SetEvent(cond->events[SIGNAL]))
1088 THROWF(system_error, 0, "SetEvent failed");
1090 xbt_os_thread_yield();
1093 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1097 EnterCriticalSection(&cond->waiters_count_lock);
1098 have_waiters = cond->waiters_count > 0;
1099 LeaveCriticalSection(&cond->waiters_count_lock);
1102 SetEvent(cond->events[BROADCAST]);
1105 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1112 if (!CloseHandle(cond->events[SIGNAL]))
1115 if (!CloseHandle(cond->events[BROADCAST]))
1118 DeleteCriticalSection(&cond->waiters_count_lock);
1123 THROWF(system_error, 0, "Error while destroying the condition");
1126 typedef struct xbt_os_sem_ {
1129 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1133 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1136 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1140 if (value > INT_MAX)
1141 THROWF(arg_error, value,
1142 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1145 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1147 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1148 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1149 strerror(GetLastError()));
1155 InitializeCriticalSection(&(res->value_lock));
1160 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1163 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1166 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1167 THROWF(system_error, GetLastError(),
1168 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1169 EnterCriticalSection(&(sem->value_lock));
1171 LeaveCriticalSection(&(sem->value_lock));
1174 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1178 double end = timeout + xbt_os_time();
1181 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1184 xbt_os_sem_acquire(sem);
1185 } else { /* timeout can be zero <-> try acquire ) */
1188 seconds = (long) floor(end);
1189 milliseconds = (long) ((end - seconds) * 1000);
1190 milliseconds += (seconds * 1000);
1192 switch (WaitForSingleObject(sem->h, milliseconds)) {
1194 EnterCriticalSection(&(sem->value_lock));
1196 LeaveCriticalSection(&(sem->value_lock));
1200 THROWF(timeout_error, GetLastError(),
1201 "semaphore %p wasn't signaled before timeout (%f)", sem,
1206 THROWF(system_error, GetLastError(),
1207 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1208 strerror(GetLastError()));
1213 void xbt_os_sem_release(xbt_os_sem_t sem)
1216 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1218 if (!ReleaseSemaphore(sem->h, 1, NULL))
1219 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1220 strerror(GetLastError()));
1221 EnterCriticalSection(&(sem->value_lock));
1223 LeaveCriticalSection(&(sem->value_lock));
1226 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1229 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1231 if (!CloseHandle(sem->h))
1232 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1233 strerror(GetLastError()));
1235 DeleteCriticalSection(&(sem->value_lock));
1241 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1244 THROWF(arg_error, EINVAL,
1245 "Cannot get the value of the NULL semaphore");
1247 EnterCriticalSection(&(sem->value_lock));
1248 *svalue = sem->value;
1249 LeaveCriticalSection(&(sem->value_lock));
1256 /** @brief Returns the amount of cores on the current host */
1257 int xbt_os_get_numcores(void) {
1259 SYSTEM_INFO sysinfo;
1260 GetSystemInfo(&sysinfo);
1261 return sysinfo.dwNumberOfProcessors;
1262 #elif defined(__APPLE__) && defined(__MACH__)
1267 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1268 sysctl(nm, 2, &count, &len, NULL, 0);
1272 sysctl(nm, 2, &count, &len, NULL, 0);
1273 if(count < 1) { count = 1; }
1277 return sysconf(_SC_NPROCESSORS_ONLN);
1282 /***** reentrant mutexes *****/
1283 typedef struct xbt_os_rmutex_ {
1284 xbt_os_mutex_t mutex;
1285 xbt_os_thread_t owner;
1287 } s_xbt_os_rmutex_t;
1289 void xbt_os_thread_set_extra_data(void *data)
1291 xbt_os_thread_self()->extra_data = data;
1294 void *xbt_os_thread_get_extra_data(void)
1296 xbt_os_thread_t self = xbt_os_thread_self();
1297 return self? self->extra_data : NULL;
1300 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1302 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1303 rmutex->mutex = xbt_os_mutex_init();
1304 rmutex->owner = NULL;
1309 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1311 xbt_os_thread_t self = xbt_os_thread_self();
1314 /* the thread module is not initialized yet */
1315 rmutex->owner = NULL;
1319 if (self != rmutex->owner) {
1320 xbt_os_mutex_acquire(rmutex->mutex);
1321 rmutex->owner = self;
1328 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1330 if (rmutex->owner == NULL) {
1331 /* the thread module was not initialized */
1335 xbt_assert(rmutex->owner == xbt_os_thread_self());
1337 if (--rmutex->count == 0) {
1338 rmutex->owner = NULL;
1339 xbt_os_mutex_release(rmutex->mutex);
1343 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1345 xbt_os_mutex_destroy(rmutex->mutex);