1 /* xbt_os_thread -- portability layer over the pthread API */
2 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD */
3 /* in SG, when using CONTEXT_UCONTEXT, xbt_os_thread_stub is used instead */
5 /* Copyright (c) 2007-2014. The SimGrid Team.
6 * All rights reserved. */
8 /* This program is free software; you can redistribute it and/or modify it
9 * under the terms of the license (GNU LGPL) which comes with this package. */
11 #include "internal_config.h"
12 #include "xbt/sysdep.h"
14 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
16 #include "xbt/xbt_os_time.h" /* Portable time facilities */
17 #include "xbt/xbt_os_thread.h" /* This module */
18 #include "xbt_modinter.h" /* Initialization/finalization of this module */
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
21 "Synchronization mechanism (OS-level)");
23 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
27 #include <semaphore.h>
29 #ifdef HAVE_MUTEX_TIMEDLOCK
30 /* redefine the function header since we fail to get this from system headers on amd (at least) */
31 int pthread_mutex_timedlock(pthread_mutex_t * mutex,
32 const struct timespec *abs_timeout);
36 /* use named sempahore when sem_init() does not work */
38 static int next_sem_ID = 0;
39 static xbt_os_mutex_t next_sem_ID_lock;
42 typedef struct xbt_os_thread_ {
47 pvoid_f_pvoid_t start_routine;
48 xbt_running_ctx_t *running_ctx;
51 static xbt_os_thread_t main_thread = NULL;
53 /* thread-specific data containing the xbt_os_thread_t structure */
54 static pthread_key_t xbt_self_thread_key;
55 static int thread_mod_inited = 0;
57 /* defaults attribute for pthreads */
58 //FIXME: find where to put this
59 static pthread_attr_t thread_attr;
61 /* frees the xbt_os_thread_t corresponding to the current thread */
62 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
64 if (thread == main_thread) /* just killed main thread */
67 free(thread->running_ctx);
72 /* callback: context fetching */
73 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
75 return xbt_os_thread_self()->running_ctx;
78 /* callback: termination */
79 static void _os_thread_ex_terminate(xbt_ex_t * e)
83 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
86 void xbt_os_thread_mod_preinit(void)
90 if (thread_mod_inited)
93 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
94 THROWF(system_error, errcode,
95 "pthread_key_create failed for xbt_self_thread_key");
97 main_thread = xbt_new(s_xbt_os_thread_t, 1);
98 main_thread->name = (char *) "main";
99 main_thread->start_routine = NULL;
100 main_thread->param = NULL;
101 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
102 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
104 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
105 THROWF(system_error, errcode,
106 "pthread_setspecific failed for xbt_self_thread_key");
108 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
109 __xbt_ex_terminate = _os_thread_ex_terminate;
111 pthread_attr_init(&thread_attr);
113 thread_mod_inited = 1;
115 #ifndef HAVE_SEM_INIT
116 next_sem_ID_lock = xbt_os_mutex_init();
121 void xbt_os_thread_mod_postexit(void)
123 /* FIXME: don't try to free our key on shutdown.
124 Valgrind detects no leak if we don't, and whine if we try to */
127 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
128 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
129 free(main_thread->running_ctx);
132 thread_mod_inited = 0;
133 #ifndef HAVE_SEM_INIT
134 xbt_os_mutex_destroy(next_sem_ID_lock);
137 /* Restore the default exception setup */
138 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
139 __xbt_ex_terminate = &__xbt_ex_terminate_default;
142 /* this function is critical to tesh+mmalloc, don't mess with it */
143 int xbt_os_thread_atfork(void (*prepare)(void),
144 void (*parent)(void), void (*child)(void))
147 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
149 return pthread_atfork(prepare, parent, child);
153 static void *wrapper_start_routine(void *s)
155 xbt_os_thread_t t = s;
158 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
159 THROWF(system_error, errcode,
160 "pthread_setspecific failed for xbt_self_thread_key");
162 void *res = t->start_routine(t->param);
164 xbt_os_thread_free_thread_data(t);
169 xbt_os_thread_t xbt_os_thread_create(const char *name,
170 pvoid_f_pvoid_t start_routine,
176 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
177 res_thread->detached = 0;
178 res_thread->name = xbt_strdup(name);
179 res_thread->start_routine = start_routine;
180 res_thread->param = param;
181 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
182 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
183 res_thread->extra_data = extra_data;
185 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
186 wrapper_start_routine, res_thread)))
187 THROWF(system_error, errcode,
188 "pthread_create failed: %s", strerror(errcode));
196 void xbt_os_thread_setstacksize(int stack_size)
198 size_t alignment[] = {
200 #ifdef PTHREAD_STACK_MIN
210 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
213 res = pthread_attr_setstacksize(&thread_attr, sz);
215 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
216 /* Invalid size, try again with next multiple of alignment[i]. */
217 size_t rem = sz % alignment[i];
218 if (rem != 0 || sz == 0) {
219 size_t sz2 = sz - rem + alignment[i];
220 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
223 res = pthread_attr_setstacksize(&thread_attr, sz);
228 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
230 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
233 void xbt_os_thread_setguardsize(int guard_size)
236 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
238 size_t sz = guard_size;
239 int res = pthread_attr_setguardsize(&thread_attr, sz);
241 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
245 const char *xbt_os_thread_name(xbt_os_thread_t t)
250 const char *xbt_os_thread_self_name(void)
252 xbt_os_thread_t me = xbt_os_thread_self();
253 return me ? me->name : "main";
256 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
261 if ((errcode = pthread_join(thread->t, thread_return)))
262 THROWF(system_error, errcode, "pthread_join failed: %s",
264 xbt_os_thread_free_thread_data(thread);
267 void xbt_os_thread_exit(int *retval)
269 pthread_exit(retval);
272 xbt_os_thread_t xbt_os_thread_self(void)
276 if (!thread_mod_inited)
279 res = pthread_getspecific(xbt_self_thread_key);
284 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
287 if ((errcode = pthread_key_create(key, NULL)))
288 THROWF(system_error, errcode, "pthread_key_create failed");
291 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
294 if ((errcode = pthread_setspecific(key, value)))
295 THROWF(system_error, errcode, "pthread_setspecific failed");
298 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
299 return pthread_getspecific(key);
302 void xbt_os_thread_detach(xbt_os_thread_t thread)
304 thread->detached = 1;
305 pthread_detach(thread->t);
309 void xbt_os_thread_yield(void)
314 void xbt_os_thread_cancel(xbt_os_thread_t t)
316 pthread_cancel(t->t);
319 /****** mutex related functions ******/
320 typedef struct xbt_os_mutex_ {
321 /* KEEP IT IN SYNC WITH xbt_thread.c */
328 xbt_os_mutex_t xbt_os_mutex_init(void)
330 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
333 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
334 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
340 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
344 if ((errcode = pthread_mutex_lock(&(mutex->m))))
345 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
346 mutex, strerror(errcode));
350 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
355 xbt_os_mutex_acquire(mutex);
357 } else if (delay == 0) {
358 errcode = pthread_mutex_trylock(&(mutex->m));
364 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
366 THROWF(system_error, errcode,
367 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
374 #ifdef HAVE_MUTEX_TIMEDLOCK
375 struct timespec ts_end;
376 double end = delay + xbt_os_time();
378 ts_end.tv_sec = (time_t) floor(end);
379 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
380 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
382 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
384 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
385 double start = xbt_os_time();
387 errcode = pthread_mutex_trylock(&(mutex->m));
388 if (errcode == EBUSY)
389 xbt_os_thread_yield();
390 } while (errcode == EBUSY && xbt_os_time() - start < delay);
392 if (errcode == EBUSY)
395 #endif /* HAVE_MUTEX_TIMEDLOCK */
402 THROWF(timeout_error, delay,
403 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
406 THROWF(system_error, errcode,
407 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
413 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
417 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
418 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
419 mutex, strerror(errcode));
422 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
429 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
430 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
431 mutex, strerror(errcode));
435 /***** condition related functions *****/
436 typedef struct xbt_os_cond_ {
437 /* KEEP IT IN SYNC WITH xbt_thread.c */
441 xbt_os_cond_t xbt_os_cond_init(void)
443 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
445 if ((errcode = pthread_cond_init(&(res->c), NULL)))
446 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
452 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
455 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
456 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
457 cond, mutex, strerror(errcode));
461 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
465 struct timespec ts_end;
466 double end = delay + xbt_os_time();
469 xbt_os_cond_wait(cond, mutex);
471 ts_end.tv_sec = (time_t) floor(end);
472 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
473 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
476 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
480 THROWF(timeout_error, errcode,
481 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
484 THROWF(system_error, errcode,
485 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
486 delay, strerror(errcode));
491 void xbt_os_cond_signal(xbt_os_cond_t cond)
494 if ((errcode = pthread_cond_signal(&(cond->c))))
495 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
496 cond, strerror(errcode));
499 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
502 if ((errcode = pthread_cond_broadcast(&(cond->c))))
503 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
504 cond, strerror(errcode));
507 void xbt_os_cond_destroy(xbt_os_cond_t cond)
514 if ((errcode = pthread_cond_destroy(&(cond->c))))
515 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
516 cond, strerror(errcode));
520 void *xbt_os_thread_getparam(void)
522 xbt_os_thread_t t = xbt_os_thread_self();
523 return t ? t->param : NULL;
526 typedef struct xbt_os_sem_ {
527 #ifndef HAVE_SEM_INIT
535 #define SEM_FAILED (-1)
538 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
540 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
542 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
543 * Any attempt to use it leads to ENOSYS (function not implemented).
544 * If such a prehistoric system is detected, do the job with sem_open instead
547 if (sem_init(&(res->s), 0, value) != 0)
548 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
551 #else /* damn, no sem_init(). Reimplement it */
553 xbt_os_mutex_acquire(next_sem_ID_lock);
554 res->name = bprintf("/%d", ++next_sem_ID);
555 xbt_os_mutex_release(next_sem_ID_lock);
557 res->ps = sem_open(res->name, O_CREAT, 0644, value);
558 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
559 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
560 res->name[13] = '\0';
561 res->ps = sem_open(res->name, O_CREAT, 0644, value);
563 if ((res->ps == (sem_t *) SEM_FAILED))
564 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
566 /* Remove the name from the semaphore namespace: we never join on it */
567 if (sem_unlink(res->name) < 0)
568 THROWF(system_error, errno, "sem_unlink() failed: %s",
576 void xbt_os_sem_acquire(xbt_os_sem_t sem)
579 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
580 if (sem_wait(sem->ps) < 0)
581 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
584 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
589 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
592 xbt_os_sem_acquire(sem);
593 } else if (delay == 0) {
594 errcode = sem_trywait(sem->ps);
600 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
602 THROWF(system_error, errcode,
603 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
609 struct timespec ts_end;
610 double end = delay + xbt_os_time();
612 ts_end.tv_sec = (time_t) floor(end);
613 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
614 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
615 errcode = sem_timedwait(sem->s, &ts_end);
617 #else /* Okay, reimplement this function then */
618 double start = xbt_os_time();
620 errcode = sem_trywait(sem->ps);
621 if (errcode == EBUSY)
622 xbt_os_thread_yield();
623 } while (errcode == EBUSY && xbt_os_time() - start < delay);
625 if (errcode == EBUSY)
634 THROWF(timeout_error, delay,
635 "semaphore %p wasn't signaled before timeout (%f)", sem,
639 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
640 delay, strerror(errcode));
645 void xbt_os_sem_release(xbt_os_sem_t sem)
648 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
650 if (sem_post(sem->ps) < 0)
651 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
654 void xbt_os_sem_destroy(xbt_os_sem_t sem)
657 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
660 if (sem_destroy(sem->ps) < 0)
661 THROWF(system_error, errno, "sem_destroy() failed: %s",
664 if (sem_close(sem->ps) < 0)
665 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
672 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
675 THROWF(arg_error, EINVAL,
676 "Cannot get the value of the NULL semaphore");
678 if (sem_getvalue(&(sem->s), svalue) < 0)
679 THROWF(system_error, errno, "sem_getvalue() failed: %s",
683 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
685 #elif defined(_XBT_WIN32)
689 typedef struct xbt_os_thread_ {
691 HANDLE handle; /* the win thread handle */
692 unsigned long id; /* the win thread id */
693 pvoid_f_pvoid_t start_routine;
698 /* so we can specify the size of the stack of the threads */
699 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
700 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
703 /* the default size of the stack of the threads (in bytes)*/
704 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
705 static int stack_size=0;
706 /* key to the TLS containing the xbt_os_thread_t structure */
707 static unsigned long xbt_self_thread_key;
709 void xbt_os_thread_mod_preinit(void)
711 xbt_self_thread_key = TlsAlloc();
714 void xbt_os_thread_mod_postexit(void)
717 if (!TlsFree(xbt_self_thread_key))
718 THROWF(system_error, (int) GetLastError(),
719 "TlsFree() failed to cleanup the thread submodule");
722 int xbt_os_thread_atfork(void (*prepare)(void),
723 void (*parent)(void), void (*child)(void))
728 static DWORD WINAPI wrapper_start_routine(void *s)
730 xbt_os_thread_t t = (xbt_os_thread_t) s;
733 if (!TlsSetValue(xbt_self_thread_key, t))
734 THROWF(system_error, (int) GetLastError(),
735 "TlsSetValue of data describing the created thread failed");
737 rv = (DWORD *) ((t->start_routine) (t->param));
744 xbt_os_thread_t xbt_os_thread_create(const char *name,
745 pvoid_f_pvoid_t start_routine,
750 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
752 t->name = xbt_strdup(name);
753 t->start_routine = start_routine;
755 t->extra_data = extra_data;
756 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
757 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
758 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
762 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
768 void xbt_os_thread_setstacksize(int size)
773 void xbt_os_thread_setguardsize(int size)
775 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
778 const char *xbt_os_thread_name(xbt_os_thread_t t)
783 const char *xbt_os_thread_self_name(void)
785 xbt_os_thread_t t = xbt_os_thread_self();
786 return t ? t->name : "main";
789 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
792 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
793 THROWF(system_error, (int) GetLastError(),
794 "WaitForSingleObject failed");
798 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
799 THROWF(system_error, (int) GetLastError(),
800 "GetExitCodeThread failed");
803 CloseHandle(thread->handle);
810 void xbt_os_thread_exit(int *retval)
818 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
823 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
825 if (!TlsSetValue(key, value))
826 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
829 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
830 return TlsGetValue(key);
833 void xbt_os_thread_detach(xbt_os_thread_t thread)
839 xbt_os_thread_t xbt_os_thread_self(void)
841 return TlsGetValue(xbt_self_thread_key);
844 void *xbt_os_thread_getparam(void)
846 xbt_os_thread_t t = xbt_os_thread_self();
851 void xbt_os_thread_yield(void)
856 void xbt_os_thread_cancel(xbt_os_thread_t t)
858 if (!TerminateThread(t->handle, 0))
859 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
862 /****** mutex related functions ******/
863 typedef struct xbt_os_mutex_ {
864 /* KEEP IT IN SYNC WITH xbt_thread.c */
865 CRITICAL_SECTION lock;
868 xbt_os_mutex_t xbt_os_mutex_init(void)
870 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
872 /* initialize the critical section object */
873 InitializeCriticalSection(&(res->lock));
878 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
880 EnterCriticalSection(&mutex->lock);
883 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
888 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
891 LeaveCriticalSection(&mutex->lock);
895 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
901 DeleteCriticalSection(&mutex->lock);
905 /***** condition related functions *****/
906 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
912 typedef struct xbt_os_cond_ {
913 /* KEEP IT IN SYNC WITH xbt_thread.c */
914 HANDLE events[MAX_EVENTS];
916 unsigned int waiters_count; /* the number of waiters */
917 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
920 xbt_os_cond_t xbt_os_cond_init(void)
923 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
925 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
927 /* initialize the critical section object */
928 InitializeCriticalSection(&res->waiters_count_lock);
930 res->waiters_count = 0;
932 /* Create an auto-reset event */
933 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
935 if (!res->events[SIGNAL]) {
936 DeleteCriticalSection(&res->waiters_count_lock);
938 THROWF(system_error, 0, "CreateEvent failed for the signals");
941 /* Create a manual-reset event. */
942 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
944 if (!res->events[BROADCAST]) {
946 DeleteCriticalSection(&res->waiters_count_lock);
947 CloseHandle(res->events[SIGNAL]);
949 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
955 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
958 unsigned long wait_result;
961 /* lock the threads counter and increment it */
962 EnterCriticalSection(&cond->waiters_count_lock);
963 cond->waiters_count++;
964 LeaveCriticalSection(&cond->waiters_count_lock);
966 /* unlock the mutex associate with the condition */
967 LeaveCriticalSection(&mutex->lock);
969 /* wait for a signal (broadcast or no) */
970 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
972 if (wait_result == WAIT_FAILED)
973 THROWF(system_error, 0,
974 "WaitForMultipleObjects failed, so we cannot wait on the condition");
976 /* we have a signal lock the condition */
977 EnterCriticalSection(&cond->waiters_count_lock);
978 cond->waiters_count--;
980 /* it's the last waiter or it's a broadcast ? */
981 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
982 && (cond->waiters_count == 0));
984 LeaveCriticalSection(&cond->waiters_count_lock);
986 /* yes it's the last waiter or it's a broadcast
987 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
991 if (!ResetEvent(cond->events[BROADCAST]))
992 THROWF(system_error, 0, "ResetEvent failed");
994 /* relock the mutex associated with the condition in accordance with the posix thread specification */
995 EnterCriticalSection(&mutex->lock);
998 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1002 unsigned long wait_result = WAIT_TIMEOUT;
1004 unsigned long end = (unsigned long) (delay * 1000);
1008 xbt_os_cond_wait(cond, mutex);
1010 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1011 &(mutex->lock), end);
1013 /* lock the threads counter and increment it */
1014 EnterCriticalSection(&cond->waiters_count_lock);
1015 cond->waiters_count++;
1016 LeaveCriticalSection(&cond->waiters_count_lock);
1018 /* unlock the mutex associate with the condition */
1019 LeaveCriticalSection(&mutex->lock);
1020 /* wait for a signal (broadcast or no) */
1022 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1024 switch (wait_result) {
1026 THROWF(timeout_error, GetLastError(),
1027 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1028 cond, mutex, delay);
1030 THROWF(system_error, GetLastError(),
1031 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1034 /* we have a signal lock the condition */
1035 EnterCriticalSection(&cond->waiters_count_lock);
1036 cond->waiters_count--;
1038 /* it's the last waiter or it's a broadcast ? */
1039 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1040 && (cond->waiters_count == 0));
1042 LeaveCriticalSection(&cond->waiters_count_lock);
1044 /* yes it's the last waiter or it's a broadcast
1045 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1049 if (!ResetEvent(cond->events[BROADCAST]))
1050 THROWF(system_error, 0, "ResetEvent failed");
1052 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1053 EnterCriticalSection(&mutex->lock);
1055 /*THROW_UNIMPLEMENTED; */
1058 void xbt_os_cond_signal(xbt_os_cond_t cond)
1062 EnterCriticalSection(&cond->waiters_count_lock);
1063 have_waiters = cond->waiters_count > 0;
1064 LeaveCriticalSection(&cond->waiters_count_lock);
1067 if (!SetEvent(cond->events[SIGNAL]))
1068 THROWF(system_error, 0, "SetEvent failed");
1070 xbt_os_thread_yield();
1073 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1077 EnterCriticalSection(&cond->waiters_count_lock);
1078 have_waiters = cond->waiters_count > 0;
1079 LeaveCriticalSection(&cond->waiters_count_lock);
1082 SetEvent(cond->events[BROADCAST]);
1085 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1092 if (!CloseHandle(cond->events[SIGNAL]))
1095 if (!CloseHandle(cond->events[BROADCAST]))
1098 DeleteCriticalSection(&cond->waiters_count_lock);
1103 THROWF(system_error, 0, "Error while destroying the condition");
1106 typedef struct xbt_os_sem_ {
1109 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1113 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1116 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1120 if (value > INT_MAX)
1121 THROWF(arg_error, value,
1122 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1125 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1127 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1128 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1129 strerror(GetLastError()));
1135 InitializeCriticalSection(&(res->value_lock));
1140 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1143 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1146 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1147 THROWF(system_error, GetLastError(),
1148 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1149 EnterCriticalSection(&(sem->value_lock));
1151 LeaveCriticalSection(&(sem->value_lock));
1154 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1158 double end = timeout + xbt_os_time();
1161 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1164 xbt_os_sem_acquire(sem);
1165 } else { /* timeout can be zero <-> try acquire ) */
1168 seconds = (long) floor(end);
1169 milliseconds = (long) ((end - seconds) * 1000);
1170 milliseconds += (seconds * 1000);
1172 switch (WaitForSingleObject(sem->h, milliseconds)) {
1174 EnterCriticalSection(&(sem->value_lock));
1176 LeaveCriticalSection(&(sem->value_lock));
1180 THROWF(timeout_error, GetLastError(),
1181 "semaphore %p wasn't signaled before timeout (%f)", sem,
1186 THROWF(system_error, GetLastError(),
1187 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1188 strerror(GetLastError()));
1193 void xbt_os_sem_release(xbt_os_sem_t sem)
1196 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1198 if (!ReleaseSemaphore(sem->h, 1, NULL))
1199 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1200 strerror(GetLastError()));
1201 EnterCriticalSection(&(sem->value_lock));
1203 LeaveCriticalSection(&(sem->value_lock));
1206 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1209 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1211 if (!CloseHandle(sem->h))
1212 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1213 strerror(GetLastError()));
1215 DeleteCriticalSection(&(sem->value_lock));
1221 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1224 THROWF(arg_error, EINVAL,
1225 "Cannot get the value of the NULL semaphore");
1227 EnterCriticalSection(&(sem->value_lock));
1228 *svalue = sem->value;
1229 LeaveCriticalSection(&(sem->value_lock));
1236 /** @brief Returns the amount of cores on the current host */
1237 int xbt_os_get_numcores(void) {
1239 SYSTEM_INFO sysinfo;
1240 GetSystemInfo(&sysinfo);
1241 return sysinfo.dwNumberOfProcessors;
1247 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1248 sysctl(nm, 2, &count, &len, NULL, 0);
1252 sysctl(nm, 2, &count, &len, NULL, 0);
1253 if(count < 1) { count = 1; }
1257 return sysconf(_SC_NPROCESSORS_ONLN);
1262 /***** reentrant mutexes *****/
1263 typedef struct xbt_os_rmutex_ {
1264 xbt_os_mutex_t mutex;
1265 xbt_os_thread_t owner;
1267 } s_xbt_os_rmutex_t;
1269 void xbt_os_thread_set_extra_data(void *data)
1271 xbt_os_thread_self()->extra_data = data;
1274 void *xbt_os_thread_get_extra_data(void)
1276 xbt_os_thread_t self = xbt_os_thread_self();
1277 return self? self->extra_data : NULL;
1280 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1282 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1283 rmutex->mutex = xbt_os_mutex_init();
1284 rmutex->owner = NULL;
1289 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1291 xbt_os_thread_t self = xbt_os_thread_self();
1294 /* the thread module is not initialized yet */
1295 rmutex->owner = NULL;
1299 if (self != rmutex->owner) {
1300 xbt_os_mutex_acquire(rmutex->mutex);
1301 rmutex->owner = self;
1308 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1310 if (rmutex->owner == NULL) {
1311 /* the thread module was not initialized */
1315 xbt_assert(rmutex->owner == xbt_os_thread_self());
1317 if (--rmutex->count == 0) {
1318 rmutex->owner = NULL;
1319 xbt_os_mutex_release(rmutex->mutex);
1323 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1325 xbt_os_mutex_destroy(rmutex->mutex);