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>
34 /* use named sempahore when sem_init() does not work */
36 static int next_sem_ID = 0;
37 static xbt_os_mutex_t next_sem_ID_lock;
40 typedef struct xbt_os_thread_ {
45 pvoid_f_pvoid_t start_routine;
46 xbt_running_ctx_t *running_ctx;
49 static xbt_os_thread_t main_thread = NULL;
51 /* thread-specific data containing the xbt_os_thread_t structure */
52 static pthread_key_t xbt_self_thread_key;
53 static int thread_mod_inited = 0;
55 /* defaults attribute for pthreads */
56 //FIXME: find where to put this
57 static pthread_attr_t thread_attr;
59 /* frees the xbt_os_thread_t corresponding to the current thread */
60 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
62 if (thread == main_thread) /* just killed main thread */
65 free(thread->running_ctx);
70 /* callback: context fetching */
71 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
73 return xbt_os_thread_self()->running_ctx;
76 /* callback: termination */
77 static void _os_thread_ex_terminate(xbt_ex_t * e)
81 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
84 void xbt_os_thread_mod_preinit(void)
88 if (thread_mod_inited)
91 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
92 THROWF(system_error, errcode,
93 "pthread_key_create failed for xbt_self_thread_key");
95 main_thread = xbt_new(s_xbt_os_thread_t, 1);
96 main_thread->name = (char *) "main";
97 main_thread->start_routine = NULL;
98 main_thread->param = NULL;
99 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
100 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
102 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
103 THROWF(system_error, errcode,
104 "pthread_setspecific failed for xbt_self_thread_key");
106 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
107 __xbt_ex_terminate = _os_thread_ex_terminate;
109 pthread_attr_init(&thread_attr);
111 thread_mod_inited = 1;
113 #ifndef HAVE_SEM_INIT
114 next_sem_ID_lock = xbt_os_mutex_init();
119 void xbt_os_thread_mod_postexit(void)
121 /* FIXME: don't try to free our key on shutdown.
122 Valgrind detects no leak if we don't, and whine if we try to */
125 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
126 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
127 free(main_thread->running_ctx);
130 thread_mod_inited = 0;
131 #ifndef HAVE_SEM_INIT
132 xbt_os_mutex_destroy(next_sem_ID_lock);
135 /* Restore the default exception setup */
136 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
137 __xbt_ex_terminate = &__xbt_ex_terminate_default;
140 /* this function is critical to tesh+mmalloc, don't mess with it */
141 int xbt_os_thread_atfork(void (*prepare)(void),
142 void (*parent)(void), void (*child)(void))
145 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
147 return pthread_atfork(prepare, parent, child);
151 static void *wrapper_start_routine(void *s)
153 xbt_os_thread_t t = s;
156 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
157 THROWF(system_error, errcode,
158 "pthread_setspecific failed for xbt_self_thread_key");
160 void *res = t->start_routine(t->param);
162 xbt_os_thread_free_thread_data(t);
167 xbt_os_thread_t xbt_os_thread_create(const char *name,
168 pvoid_f_pvoid_t start_routine,
174 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
175 res_thread->detached = 0;
176 res_thread->name = xbt_strdup(name);
177 res_thread->start_routine = start_routine;
178 res_thread->param = param;
179 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
180 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
181 res_thread->extra_data = extra_data;
183 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
184 wrapper_start_routine, res_thread)))
185 THROWF(system_error, errcode,
186 "pthread_create failed: %s", strerror(errcode));
195 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
196 pthread_t pthread = thread->t;
200 CPU_SET(cpu, &cpuset);
201 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
206 void xbt_os_thread_setstacksize(int stack_size)
208 size_t alignment[] = {
210 #ifdef PTHREAD_STACK_MIN
220 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
223 res = pthread_attr_setstacksize(&thread_attr, sz);
225 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
226 /* Invalid size, try again with next multiple of alignment[i]. */
227 size_t rem = sz % alignment[i];
228 if (rem != 0 || sz == 0) {
229 size_t sz2 = sz - rem + alignment[i];
230 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
233 res = pthread_attr_setstacksize(&thread_attr, sz);
238 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
240 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
243 void xbt_os_thread_setguardsize(int guard_size)
246 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
248 size_t sz = guard_size;
249 int res = pthread_attr_setguardsize(&thread_attr, sz);
251 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
255 const char *xbt_os_thread_name(xbt_os_thread_t t)
260 const char *xbt_os_thread_self_name(void)
262 xbt_os_thread_t me = xbt_os_thread_self();
263 return me ? me->name : "main";
266 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
271 if ((errcode = pthread_join(thread->t, thread_return)))
272 THROWF(system_error, errcode, "pthread_join failed: %s",
274 xbt_os_thread_free_thread_data(thread);
277 void xbt_os_thread_exit(int *retval)
279 pthread_exit(retval);
282 xbt_os_thread_t xbt_os_thread_self(void)
286 if (!thread_mod_inited)
289 res = pthread_getspecific(xbt_self_thread_key);
294 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
297 if ((errcode = pthread_key_create(key, NULL)))
298 THROWF(system_error, errcode, "pthread_key_create failed");
301 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
304 if ((errcode = pthread_setspecific(key, value)))
305 THROWF(system_error, errcode, "pthread_setspecific failed");
308 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
309 return pthread_getspecific(key);
312 void xbt_os_thread_detach(xbt_os_thread_t thread)
314 thread->detached = 1;
315 pthread_detach(thread->t);
319 void xbt_os_thread_yield(void)
324 void xbt_os_thread_cancel(xbt_os_thread_t t)
326 pthread_cancel(t->t);
329 /****** mutex related functions ******/
330 typedef struct xbt_os_mutex_ {
331 /* KEEP IT IN SYNC WITH xbt_thread.c */
338 xbt_os_mutex_t xbt_os_mutex_init(void)
340 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
343 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
344 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
350 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
354 if ((errcode = pthread_mutex_lock(&(mutex->m))))
355 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
356 mutex, strerror(errcode));
360 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
365 xbt_os_mutex_acquire(mutex);
367 } else if (delay == 0) {
368 errcode = pthread_mutex_trylock(&(mutex->m));
374 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
376 THROWF(system_error, errcode,
377 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
384 #ifdef HAVE_MUTEX_TIMEDLOCK
385 struct timespec ts_end;
386 double end = delay + xbt_os_time();
388 ts_end.tv_sec = (time_t) floor(end);
389 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
390 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
392 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
394 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
395 double start = xbt_os_time();
397 errcode = pthread_mutex_trylock(&(mutex->m));
398 if (errcode == EBUSY)
399 xbt_os_thread_yield();
400 } while (errcode == EBUSY && xbt_os_time() - start < delay);
402 if (errcode == EBUSY)
405 #endif /* HAVE_MUTEX_TIMEDLOCK */
412 THROWF(timeout_error, delay,
413 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
416 THROWF(system_error, errcode,
417 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
423 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
427 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
428 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
429 mutex, strerror(errcode));
432 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
439 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
440 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
441 mutex, strerror(errcode));
445 /***** condition related functions *****/
446 typedef struct xbt_os_cond_ {
447 /* KEEP IT IN SYNC WITH xbt_thread.c */
451 xbt_os_cond_t xbt_os_cond_init(void)
453 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
455 if ((errcode = pthread_cond_init(&(res->c), NULL)))
456 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
462 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
465 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
466 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
467 cond, mutex, strerror(errcode));
471 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
475 struct timespec ts_end;
476 double end = delay + xbt_os_time();
479 xbt_os_cond_wait(cond, mutex);
481 ts_end.tv_sec = (time_t) floor(end);
482 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
483 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
486 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
490 THROWF(timeout_error, errcode,
491 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
494 THROWF(system_error, errcode,
495 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
496 delay, strerror(errcode));
501 void xbt_os_cond_signal(xbt_os_cond_t cond)
504 if ((errcode = pthread_cond_signal(&(cond->c))))
505 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
506 cond, strerror(errcode));
509 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
512 if ((errcode = pthread_cond_broadcast(&(cond->c))))
513 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
514 cond, strerror(errcode));
517 void xbt_os_cond_destroy(xbt_os_cond_t cond)
524 if ((errcode = pthread_cond_destroy(&(cond->c))))
525 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
526 cond, strerror(errcode));
530 void *xbt_os_thread_getparam(void)
532 xbt_os_thread_t t = xbt_os_thread_self();
533 return t ? t->param : NULL;
536 typedef struct xbt_os_sem_ {
537 #ifndef HAVE_SEM_INIT
545 #define SEM_FAILED (-1)
548 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
550 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
552 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
553 * Any attempt to use it leads to ENOSYS (function not implemented).
554 * If such a prehistoric system is detected, do the job with sem_open instead
557 if (sem_init(&(res->s), 0, value) != 0)
558 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
561 #else /* damn, no sem_init(). Reimplement it */
563 xbt_os_mutex_acquire(next_sem_ID_lock);
564 res->name = bprintf("/%d", ++next_sem_ID);
565 xbt_os_mutex_release(next_sem_ID_lock);
567 res->ps = sem_open(res->name, O_CREAT, 0644, value);
568 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
569 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
570 res->name[13] = '\0';
571 res->ps = sem_open(res->name, O_CREAT, 0644, value);
573 if ((res->ps == (sem_t *) SEM_FAILED))
574 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
576 /* Remove the name from the semaphore namespace: we never join on it */
577 if (sem_unlink(res->name) < 0)
578 THROWF(system_error, errno, "sem_unlink() failed: %s",
586 void xbt_os_sem_acquire(xbt_os_sem_t sem)
589 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
590 if (sem_wait(sem->ps) < 0)
591 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
594 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
599 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
602 xbt_os_sem_acquire(sem);
603 } else if (delay == 0) {
604 errcode = sem_trywait(sem->ps);
610 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
612 THROWF(system_error, errcode,
613 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
619 struct timespec ts_end;
620 double end = delay + xbt_os_time();
622 ts_end.tv_sec = (time_t) floor(end);
623 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
624 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
625 errcode = sem_timedwait(sem->s, &ts_end);
627 #else /* Okay, reimplement this function then */
628 double start = xbt_os_time();
630 errcode = sem_trywait(sem->ps);
631 if (errcode == EBUSY)
632 xbt_os_thread_yield();
633 } while (errcode == EBUSY && xbt_os_time() - start < delay);
635 if (errcode == EBUSY)
644 THROWF(timeout_error, delay,
645 "semaphore %p wasn't signaled before timeout (%f)", sem,
649 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
650 delay, strerror(errcode));
655 void xbt_os_sem_release(xbt_os_sem_t sem)
658 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
660 if (sem_post(sem->ps) < 0)
661 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
664 void xbt_os_sem_destroy(xbt_os_sem_t sem)
667 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
670 if (sem_destroy(sem->ps) < 0)
671 THROWF(system_error, errno, "sem_destroy() failed: %s",
674 if (sem_close(sem->ps) < 0)
675 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
682 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
685 THROWF(arg_error, EINVAL,
686 "Cannot get the value of the NULL semaphore");
688 if (sem_getvalue(&(sem->s), svalue) < 0)
689 THROWF(system_error, errno, "sem_getvalue() failed: %s",
693 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
695 #elif defined(_XBT_WIN32)
699 typedef struct xbt_os_thread_ {
701 HANDLE handle; /* the win thread handle */
702 unsigned long id; /* the win thread id */
703 pvoid_f_pvoid_t start_routine;
708 /* so we can specify the size of the stack of the threads */
709 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
710 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
713 /* the default size of the stack of the threads (in bytes)*/
714 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
715 static int stack_size=0;
716 /* key to the TLS containing the xbt_os_thread_t structure */
717 static unsigned long xbt_self_thread_key;
719 void xbt_os_thread_mod_preinit(void)
721 xbt_self_thread_key = TlsAlloc();
724 void xbt_os_thread_mod_postexit(void)
727 if (!TlsFree(xbt_self_thread_key))
728 THROWF(system_error, (int) GetLastError(),
729 "TlsFree() failed to cleanup the thread submodule");
732 int xbt_os_thread_atfork(void (*prepare)(void),
733 void (*parent)(void), void (*child)(void))
738 static DWORD WINAPI wrapper_start_routine(void *s)
740 xbt_os_thread_t t = (xbt_os_thread_t) s;
743 if (!TlsSetValue(xbt_self_thread_key, t))
744 THROWF(system_error, (int) GetLastError(),
745 "TlsSetValue of data describing the created thread failed");
747 rv = (DWORD *) ((t->start_routine) (t->param));
754 xbt_os_thread_t xbt_os_thread_create(const char *name,
755 pvoid_f_pvoid_t start_routine,
760 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
762 t->name = xbt_strdup(name);
763 t->start_routine = start_routine;
765 t->extra_data = extra_data;
766 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
767 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
768 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
772 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
778 void xbt_os_thread_setstacksize(int size)
783 void xbt_os_thread_setguardsize(int size)
785 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
788 const char *xbt_os_thread_name(xbt_os_thread_t t)
793 const char *xbt_os_thread_self_name(void)
795 xbt_os_thread_t t = xbt_os_thread_self();
796 return t ? t->name : "main";
799 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
802 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
803 THROWF(system_error, (int) GetLastError(),
804 "WaitForSingleObject failed");
808 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
809 THROWF(system_error, (int) GetLastError(),
810 "GetExitCodeThread failed");
813 CloseHandle(thread->handle);
820 void xbt_os_thread_exit(int *retval)
828 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
833 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
835 if (!TlsSetValue(key, value))
836 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
839 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
840 return TlsGetValue(key);
843 void xbt_os_thread_detach(xbt_os_thread_t thread)
849 xbt_os_thread_t xbt_os_thread_self(void)
851 return TlsGetValue(xbt_self_thread_key);
854 void *xbt_os_thread_getparam(void)
856 xbt_os_thread_t t = xbt_os_thread_self();
861 void xbt_os_thread_yield(void)
866 void xbt_os_thread_cancel(xbt_os_thread_t t)
868 if (!TerminateThread(t->handle, 0))
869 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
872 /****** mutex related functions ******/
873 typedef struct xbt_os_mutex_ {
874 /* KEEP IT IN SYNC WITH xbt_thread.c */
875 CRITICAL_SECTION lock;
878 xbt_os_mutex_t xbt_os_mutex_init(void)
880 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
882 /* initialize the critical section object */
883 InitializeCriticalSection(&(res->lock));
888 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
890 EnterCriticalSection(&mutex->lock);
893 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
898 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
901 LeaveCriticalSection(&mutex->lock);
905 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
911 DeleteCriticalSection(&mutex->lock);
915 /***** condition related functions *****/
916 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
922 typedef struct xbt_os_cond_ {
923 /* KEEP IT IN SYNC WITH xbt_thread.c */
924 HANDLE events[MAX_EVENTS];
926 unsigned int waiters_count; /* the number of waiters */
927 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
930 xbt_os_cond_t xbt_os_cond_init(void)
933 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
935 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
937 /* initialize the critical section object */
938 InitializeCriticalSection(&res->waiters_count_lock);
940 res->waiters_count = 0;
942 /* Create an auto-reset event */
943 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
945 if (!res->events[SIGNAL]) {
946 DeleteCriticalSection(&res->waiters_count_lock);
948 THROWF(system_error, 0, "CreateEvent failed for the signals");
951 /* Create a manual-reset event. */
952 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
954 if (!res->events[BROADCAST]) {
956 DeleteCriticalSection(&res->waiters_count_lock);
957 CloseHandle(res->events[SIGNAL]);
959 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
965 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
968 unsigned long wait_result;
971 /* lock the threads counter and increment it */
972 EnterCriticalSection(&cond->waiters_count_lock);
973 cond->waiters_count++;
974 LeaveCriticalSection(&cond->waiters_count_lock);
976 /* unlock the mutex associate with the condition */
977 LeaveCriticalSection(&mutex->lock);
979 /* wait for a signal (broadcast or no) */
980 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
982 if (wait_result == WAIT_FAILED)
983 THROWF(system_error, 0,
984 "WaitForMultipleObjects failed, so we cannot wait on the condition");
986 /* we have a signal lock the condition */
987 EnterCriticalSection(&cond->waiters_count_lock);
988 cond->waiters_count--;
990 /* it's the last waiter or it's a broadcast ? */
991 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
992 && (cond->waiters_count == 0));
994 LeaveCriticalSection(&cond->waiters_count_lock);
996 /* yes it's the last waiter or it's a broadcast
997 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1001 if (!ResetEvent(cond->events[BROADCAST]))
1002 THROWF(system_error, 0, "ResetEvent failed");
1004 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1005 EnterCriticalSection(&mutex->lock);
1008 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1012 unsigned long wait_result = WAIT_TIMEOUT;
1014 unsigned long end = (unsigned long) (delay * 1000);
1018 xbt_os_cond_wait(cond, mutex);
1020 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1021 &(mutex->lock), end);
1023 /* lock the threads counter and increment it */
1024 EnterCriticalSection(&cond->waiters_count_lock);
1025 cond->waiters_count++;
1026 LeaveCriticalSection(&cond->waiters_count_lock);
1028 /* unlock the mutex associate with the condition */
1029 LeaveCriticalSection(&mutex->lock);
1030 /* wait for a signal (broadcast or no) */
1032 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1034 switch (wait_result) {
1036 THROWF(timeout_error, GetLastError(),
1037 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1038 cond, mutex, delay);
1040 THROWF(system_error, GetLastError(),
1041 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1044 /* we have a signal lock the condition */
1045 EnterCriticalSection(&cond->waiters_count_lock);
1046 cond->waiters_count--;
1048 /* it's the last waiter or it's a broadcast ? */
1049 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1050 && (cond->waiters_count == 0));
1052 LeaveCriticalSection(&cond->waiters_count_lock);
1054 /* yes it's the last waiter or it's a broadcast
1055 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1059 if (!ResetEvent(cond->events[BROADCAST]))
1060 THROWF(system_error, 0, "ResetEvent failed");
1062 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1063 EnterCriticalSection(&mutex->lock);
1065 /*THROW_UNIMPLEMENTED; */
1068 void xbt_os_cond_signal(xbt_os_cond_t cond)
1072 EnterCriticalSection(&cond->waiters_count_lock);
1073 have_waiters = cond->waiters_count > 0;
1074 LeaveCriticalSection(&cond->waiters_count_lock);
1077 if (!SetEvent(cond->events[SIGNAL]))
1078 THROWF(system_error, 0, "SetEvent failed");
1080 xbt_os_thread_yield();
1083 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1087 EnterCriticalSection(&cond->waiters_count_lock);
1088 have_waiters = cond->waiters_count > 0;
1089 LeaveCriticalSection(&cond->waiters_count_lock);
1092 SetEvent(cond->events[BROADCAST]);
1095 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1102 if (!CloseHandle(cond->events[SIGNAL]))
1105 if (!CloseHandle(cond->events[BROADCAST]))
1108 DeleteCriticalSection(&cond->waiters_count_lock);
1113 THROWF(system_error, 0, "Error while destroying the condition");
1116 typedef struct xbt_os_sem_ {
1119 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1123 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1126 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1130 if (value > INT_MAX)
1131 THROWF(arg_error, value,
1132 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1135 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1137 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1138 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1139 strerror(GetLastError()));
1145 InitializeCriticalSection(&(res->value_lock));
1150 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1153 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1156 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1157 THROWF(system_error, GetLastError(),
1158 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1159 EnterCriticalSection(&(sem->value_lock));
1161 LeaveCriticalSection(&(sem->value_lock));
1164 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1168 double end = timeout + xbt_os_time();
1171 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1174 xbt_os_sem_acquire(sem);
1175 } else { /* timeout can be zero <-> try acquire ) */
1178 seconds = (long) floor(end);
1179 milliseconds = (long) ((end - seconds) * 1000);
1180 milliseconds += (seconds * 1000);
1182 switch (WaitForSingleObject(sem->h, milliseconds)) {
1184 EnterCriticalSection(&(sem->value_lock));
1186 LeaveCriticalSection(&(sem->value_lock));
1190 THROWF(timeout_error, GetLastError(),
1191 "semaphore %p wasn't signaled before timeout (%f)", sem,
1196 THROWF(system_error, GetLastError(),
1197 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1198 strerror(GetLastError()));
1203 void xbt_os_sem_release(xbt_os_sem_t sem)
1206 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1208 if (!ReleaseSemaphore(sem->h, 1, NULL))
1209 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1210 strerror(GetLastError()));
1211 EnterCriticalSection(&(sem->value_lock));
1213 LeaveCriticalSection(&(sem->value_lock));
1216 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1219 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1221 if (!CloseHandle(sem->h))
1222 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1223 strerror(GetLastError()));
1225 DeleteCriticalSection(&(sem->value_lock));
1231 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1234 THROWF(arg_error, EINVAL,
1235 "Cannot get the value of the NULL semaphore");
1237 EnterCriticalSection(&(sem->value_lock));
1238 *svalue = sem->value;
1239 LeaveCriticalSection(&(sem->value_lock));
1246 /** @brief Returns the amount of cores on the current host */
1247 int xbt_os_get_numcores(void) {
1249 SYSTEM_INFO sysinfo;
1250 GetSystemInfo(&sysinfo);
1251 return sysinfo.dwNumberOfProcessors;
1257 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1258 sysctl(nm, 2, &count, &len, NULL, 0);
1262 sysctl(nm, 2, &count, &len, NULL, 0);
1263 if(count < 1) { count = 1; }
1267 return sysconf(_SC_NPROCESSORS_ONLN);
1272 /***** reentrant mutexes *****/
1273 typedef struct xbt_os_rmutex_ {
1274 xbt_os_mutex_t mutex;
1275 xbt_os_thread_t owner;
1277 } s_xbt_os_rmutex_t;
1279 void xbt_os_thread_set_extra_data(void *data)
1281 xbt_os_thread_self()->extra_data = data;
1284 void *xbt_os_thread_get_extra_data(void)
1286 xbt_os_thread_t self = xbt_os_thread_self();
1287 return self? self->extra_data : NULL;
1290 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1292 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1293 rmutex->mutex = xbt_os_mutex_init();
1294 rmutex->owner = NULL;
1299 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1301 xbt_os_thread_t self = xbt_os_thread_self();
1304 /* the thread module is not initialized yet */
1305 rmutex->owner = NULL;
1309 if (self != rmutex->owner) {
1310 xbt_os_mutex_acquire(rmutex->mutex);
1311 rmutex->owner = self;
1318 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1320 if (rmutex->owner == NULL) {
1321 /* the thread module was not initialized */
1325 xbt_assert(rmutex->owner == xbt_os_thread_self());
1327 if (--rmutex->count == 0) {
1328 rmutex->owner = NULL;
1329 xbt_os_mutex_release(rmutex->mutex);
1333 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1335 xbt_os_mutex_destroy(rmutex->mutex);