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 HAVE_UCONTEXT_CONTEXTS, xbt_os_thread_stub is used instead */
5 /* Copyright (c) 2007-2015. 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 "src/internal_config.h"
21 #include "xbt/sysdep.h"
23 #include "src/xbt/ex_interface.h" /* We play crude games with exceptions */
24 #include "src/portable.h"
25 #include "xbt/xbt_os_time.h" /* Portable time facilities */
26 #include "xbt/xbt_os_thread.h" /* This module */
27 #include "src/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 = NULL;
107 main_thread->detached = 0;
108 main_thread->name = (char *) "main";
109 main_thread->param = NULL;
110 main_thread->start_routine = NULL;
111 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
112 main_thread->extra_data = NULL;
113 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
115 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
116 THROWF(system_error, errcode,
117 "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
119 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
120 __xbt_ex_terminate = _os_thread_ex_terminate;
122 pthread_attr_init(&thread_attr);
124 thread_mod_inited = 1;
126 #ifndef HAVE_SEM_INIT
127 next_sem_ID_lock = xbt_os_mutex_init();
132 void xbt_os_thread_mod_postexit(void)
134 /* FIXME: don't try to free our key on shutdown.
135 Valgrind detects no leak if we don't, and whine if we try to */
138 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
139 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
140 free(main_thread->running_ctx);
143 thread_mod_inited = 0;
144 #ifndef HAVE_SEM_INIT
145 xbt_os_mutex_destroy(next_sem_ID_lock);
148 /* Restore the default exception setup */
149 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
150 __xbt_ex_terminate = &__xbt_ex_terminate_default;
153 /* this function is critical to tesh+mmalloc, don't mess with it */
154 int xbt_os_thread_atfork(void (*prepare)(void),
155 void (*parent)(void), void (*child)(void))
158 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
160 return pthread_atfork(prepare, parent, child);
164 static void *wrapper_start_routine(void *s)
166 xbt_os_thread_t t = s;
169 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
170 THROWF(system_error, errcode,
171 "pthread_setspecific failed for xbt_self_thread_key");
173 void *res = t->start_routine(t->param);
175 xbt_os_thread_free_thread_data(t);
180 xbt_os_thread_t xbt_os_thread_create(const char *name,
181 pvoid_f_pvoid_t start_routine,
187 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
188 res_thread->detached = 0;
189 res_thread->name = xbt_strdup(name);
190 res_thread->start_routine = start_routine;
191 res_thread->param = param;
192 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
193 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
194 res_thread->extra_data = extra_data;
196 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
197 wrapper_start_routine, res_thread)))
198 THROWF(system_error, errcode,
199 "pthread_create failed: %s", strerror(errcode));
208 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
209 pthread_t pthread = thread->t;
213 CPU_SET(cpu, &cpuset);
214 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
219 void xbt_os_thread_setstacksize(int stack_size)
221 size_t alignment[] = {
223 #ifdef PTHREAD_STACK_MIN
233 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
236 res = pthread_attr_setstacksize(&thread_attr, sz);
238 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
239 /* Invalid size, try again with next multiple of alignment[i]. */
240 size_t rem = sz % alignment[i];
241 if (rem != 0 || sz == 0) {
242 size_t sz2 = sz - rem + alignment[i];
243 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
246 res = pthread_attr_setstacksize(&thread_attr, sz);
251 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
253 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
256 void xbt_os_thread_setguardsize(int guard_size)
259 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
261 size_t sz = guard_size;
262 int res = pthread_attr_setguardsize(&thread_attr, sz);
264 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
268 const char *xbt_os_thread_name(xbt_os_thread_t t)
273 const char *xbt_os_thread_self_name(void)
275 xbt_os_thread_t me = xbt_os_thread_self();
276 return me ? me->name : "main";
279 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
284 if ((errcode = pthread_join(thread->t, thread_return)))
285 THROWF(system_error, errcode, "pthread_join failed: %s",
287 xbt_os_thread_free_thread_data(thread);
290 void xbt_os_thread_exit(int *retval)
292 pthread_exit(retval);
295 xbt_os_thread_t xbt_os_thread_self(void)
297 if (!thread_mod_inited)
300 return pthread_getspecific(xbt_self_thread_key);
303 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
306 if ((errcode = pthread_key_create(key, NULL)))
307 THROWF(system_error, errcode, "pthread_key_create failed");
310 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
313 if ((errcode = pthread_setspecific(key, value)))
314 THROWF(system_error, errcode, "pthread_setspecific failed");
317 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
318 return pthread_getspecific(key);
321 void xbt_os_thread_detach(xbt_os_thread_t thread)
323 thread->detached = 1;
324 pthread_detach(thread->t);
328 void xbt_os_thread_yield(void)
333 void xbt_os_thread_cancel(xbt_os_thread_t t)
335 pthread_cancel(t->t);
338 /****** mutex related functions ******/
339 typedef struct xbt_os_mutex_ {
340 /* KEEP IT IN SYNC WITH xbt_thread.c */
347 xbt_os_mutex_t xbt_os_mutex_init(void)
349 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
352 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
353 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
359 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
363 if ((errcode = pthread_mutex_lock(&(mutex->m))))
364 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
365 mutex, strerror(errcode));
369 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
374 xbt_os_mutex_acquire(mutex);
376 } else if (delay == 0) {
377 errcode = pthread_mutex_trylock(&(mutex->m));
383 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
385 THROWF(system_error, errcode,
386 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
393 #ifdef HAVE_MUTEX_TIMEDLOCK
394 struct timespec ts_end;
395 double end = delay + xbt_os_time();
397 ts_end.tv_sec = (time_t) floor(end);
398 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
399 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
401 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
403 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
404 double start = xbt_os_time();
406 errcode = pthread_mutex_trylock(&(mutex->m));
407 if (errcode == EBUSY)
408 xbt_os_thread_yield();
409 } while (errcode == EBUSY && xbt_os_time() - start < delay);
411 if (errcode == EBUSY)
414 #endif /* HAVE_MUTEX_TIMEDLOCK */
421 THROWF(timeout_error, delay,
422 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
425 THROWF(system_error, errcode,
426 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
432 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
436 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
437 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
438 mutex, strerror(errcode));
441 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
448 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
449 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
450 mutex, strerror(errcode));
454 /***** condition related functions *****/
455 typedef struct xbt_os_cond_ {
456 /* KEEP IT IN SYNC WITH xbt_thread.c */
460 xbt_os_cond_t xbt_os_cond_init(void)
462 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
464 if ((errcode = pthread_cond_init(&(res->c), NULL)))
465 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
471 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
474 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
475 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
476 cond, mutex, strerror(errcode));
480 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
484 struct timespec ts_end;
485 double end = delay + xbt_os_time();
488 xbt_os_cond_wait(cond, mutex);
490 ts_end.tv_sec = (time_t) floor(end);
491 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
492 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
495 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
499 THROWF(timeout_error, errcode,
500 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
503 THROWF(system_error, errcode,
504 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
505 delay, strerror(errcode));
510 void xbt_os_cond_signal(xbt_os_cond_t cond)
513 if ((errcode = pthread_cond_signal(&(cond->c))))
514 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
515 cond, strerror(errcode));
518 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
521 if ((errcode = pthread_cond_broadcast(&(cond->c))))
522 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
523 cond, strerror(errcode));
526 void xbt_os_cond_destroy(xbt_os_cond_t cond)
533 if ((errcode = pthread_cond_destroy(&(cond->c))))
534 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
535 cond, strerror(errcode));
539 void *xbt_os_thread_getparam(void)
541 xbt_os_thread_t t = xbt_os_thread_self();
542 return t ? t->param : NULL;
545 typedef struct xbt_os_sem_ {
546 #ifndef HAVE_SEM_INIT
554 #define SEM_FAILED (-1)
557 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
559 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
561 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
562 * Any attempt to use it leads to ENOSYS (function not implemented).
563 * If such a prehistoric system is detected, do the job with sem_open instead
566 if (sem_init(&(res->s), 0, value) != 0)
567 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
570 #else /* damn, no sem_init(). Reimplement it */
572 xbt_os_mutex_acquire(next_sem_ID_lock);
573 res->name = bprintf("/%d", ++next_sem_ID);
574 xbt_os_mutex_release(next_sem_ID_lock);
576 res->ps = sem_open(res->name, O_CREAT, 0644, value);
577 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
578 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
579 res->name[13] = '\0';
580 res->ps = sem_open(res->name, O_CREAT, 0644, value);
582 if (res->ps == (sem_t *) SEM_FAILED)
583 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
585 /* Remove the name from the semaphore namespace: we never join on it */
586 if (sem_unlink(res->name) < 0)
587 THROWF(system_error, errno, "sem_unlink() failed: %s",
595 void xbt_os_sem_acquire(xbt_os_sem_t sem)
598 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
599 if (sem_wait(sem->ps) < 0)
600 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
603 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
608 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
611 xbt_os_sem_acquire(sem);
612 } else if (delay == 0) {
613 errcode = sem_trywait(sem->ps);
619 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
621 THROWF(system_error, errcode,
622 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
628 struct timespec ts_end;
629 double end = delay + xbt_os_time();
631 ts_end.tv_sec = (time_t) floor(end);
632 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
633 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
634 errcode = sem_timedwait(sem->s, &ts_end);
636 #else /* Okay, reimplement this function then */
637 double start = xbt_os_time();
639 errcode = sem_trywait(sem->ps);
640 if (errcode == EBUSY)
641 xbt_os_thread_yield();
642 } while (errcode == EBUSY && xbt_os_time() - start < delay);
644 if (errcode == EBUSY)
653 THROWF(timeout_error, delay,
654 "semaphore %p wasn't signaled before timeout (%f)", sem,
658 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
659 delay, strerror(errcode));
664 void xbt_os_sem_release(xbt_os_sem_t sem)
667 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
669 if (sem_post(sem->ps) < 0)
670 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
673 void xbt_os_sem_destroy(xbt_os_sem_t sem)
676 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
679 if (sem_destroy(sem->ps) < 0)
680 THROWF(system_error, errno, "sem_destroy() failed: %s",
683 if (sem_close(sem->ps) < 0)
684 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
691 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
694 THROWF(arg_error, EINVAL,
695 "Cannot get the value of the NULL semaphore");
697 if (sem_getvalue(&(sem->s), svalue) < 0)
698 THROWF(system_error, errno, "sem_getvalue() failed: %s",
702 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
704 #elif defined(_XBT_WIN32)
708 typedef struct xbt_os_thread_ {
710 HANDLE handle; /* the win thread handle */
711 unsigned long id; /* the win thread id */
712 pvoid_f_pvoid_t start_routine;
717 /* so we can specify the size of the stack of the threads */
718 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
719 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
722 /* the default size of the stack of the threads (in bytes)*/
723 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
724 static int stack_size=0;
725 /* key to the TLS containing the xbt_os_thread_t structure */
726 static unsigned long xbt_self_thread_key;
728 void xbt_os_thread_mod_preinit(void)
730 xbt_self_thread_key = TlsAlloc();
732 xbt_os_thread_t main_thread = xbt_new0(s_xbt_os_thread_t, 1);
733 main_thread->name = (char *) "main";
734 main_thread->start_routine = NULL;
735 main_thread->param = NULL;
737 if (!TlsSetValue(xbt_self_thread_key, main_thread))
738 THROWF(system_error, (int)GetLastError(),
739 "Impossible to set the SimGrid identity descriptor to the main thread (TlsSetValue() failed)");
743 void xbt_os_thread_mod_postexit(void)
746 if (!TlsFree(xbt_self_thread_key))
747 THROWF(system_error, (int) GetLastError(),
748 "TlsFree() failed to cleanup the thread submodule");
751 int xbt_os_thread_atfork(void (*prepare)(void),
752 void (*parent)(void), void (*child)(void))
757 static DWORD WINAPI wrapper_start_routine(void *s)
759 xbt_os_thread_t t = (xbt_os_thread_t) s;
762 if (!TlsSetValue(xbt_self_thread_key, t))
763 THROWF(system_error, (int) GetLastError(),
764 "TlsSetValue of data describing the created thread failed");
766 rv = (DWORD *) ((t->start_routine) (t->param));
773 xbt_os_thread_t xbt_os_thread_create(const char *name,
774 pvoid_f_pvoid_t start_routine,
779 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
781 t->name = xbt_strdup(name);
782 t->start_routine = start_routine;
784 t->extra_data = extra_data;
785 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
786 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
787 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
791 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
797 void xbt_os_thread_setstacksize(int size)
802 void xbt_os_thread_setguardsize(int size)
804 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
807 const char *xbt_os_thread_name(xbt_os_thread_t t)
812 const char *xbt_os_thread_self_name(void)
814 xbt_os_thread_t t = xbt_os_thread_self();
815 return t ? t->name : "main";
818 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
821 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
822 THROWF(system_error, (int) GetLastError(),
823 "WaitForSingleObject failed");
827 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
828 THROWF(system_error, (int) GetLastError(),
829 "GetExitCodeThread failed");
832 CloseHandle(thread->handle);
839 void xbt_os_thread_exit(int *retval)
847 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
852 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
854 if (!TlsSetValue(key, value))
855 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
858 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
859 return TlsGetValue(key);
862 void xbt_os_thread_detach(xbt_os_thread_t thread)
868 xbt_os_thread_t xbt_os_thread_self(void)
870 return TlsGetValue(xbt_self_thread_key);
873 void *xbt_os_thread_getparam(void)
875 xbt_os_thread_t t = xbt_os_thread_self();
880 void xbt_os_thread_yield(void)
885 void xbt_os_thread_cancel(xbt_os_thread_t t)
887 if (!TerminateThread(t->handle, 0))
888 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
891 /****** mutex related functions ******/
892 typedef struct xbt_os_mutex_ {
893 /* KEEP IT IN SYNC WITH xbt_thread.c */
894 CRITICAL_SECTION lock;
897 xbt_os_mutex_t xbt_os_mutex_init(void)
899 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
901 /* initialize the critical section object */
902 InitializeCriticalSection(&(res->lock));
907 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
909 EnterCriticalSection(&mutex->lock);
912 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
917 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
920 LeaveCriticalSection(&mutex->lock);
924 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
930 DeleteCriticalSection(&mutex->lock);
934 /***** condition related functions *****/
935 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
941 typedef struct xbt_os_cond_ {
942 /* KEEP IT IN SYNC WITH xbt_thread.c */
943 HANDLE events[MAX_EVENTS];
945 unsigned int waiters_count; /* the number of waiters */
946 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
949 xbt_os_cond_t xbt_os_cond_init(void)
952 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
954 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
956 /* initialize the critical section object */
957 InitializeCriticalSection(&res->waiters_count_lock);
959 res->waiters_count = 0;
961 /* Create an auto-reset event */
962 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
964 if (!res->events[SIGNAL]) {
965 DeleteCriticalSection(&res->waiters_count_lock);
967 THROWF(system_error, 0, "CreateEvent failed for the signals");
970 /* Create a manual-reset event. */
971 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
973 if (!res->events[BROADCAST]) {
975 DeleteCriticalSection(&res->waiters_count_lock);
976 CloseHandle(res->events[SIGNAL]);
978 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
984 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
987 unsigned long wait_result;
990 /* lock the threads counter and increment it */
991 EnterCriticalSection(&cond->waiters_count_lock);
992 cond->waiters_count++;
993 LeaveCriticalSection(&cond->waiters_count_lock);
995 /* unlock the mutex associate with the condition */
996 LeaveCriticalSection(&mutex->lock);
998 /* wait for a signal (broadcast or no) */
999 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
1001 if (wait_result == WAIT_FAILED)
1002 THROWF(system_error, 0,
1003 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1005 /* we have a signal lock the condition */
1006 EnterCriticalSection(&cond->waiters_count_lock);
1007 cond->waiters_count--;
1009 /* it's the last waiter or it's a broadcast ? */
1010 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1011 && (cond->waiters_count == 0));
1013 LeaveCriticalSection(&cond->waiters_count_lock);
1015 /* yes it's the last waiter or it's a broadcast
1016 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1020 if (!ResetEvent(cond->events[BROADCAST]))
1021 THROWF(system_error, 0, "ResetEvent failed");
1023 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1024 EnterCriticalSection(&mutex->lock);
1027 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1031 unsigned long wait_result = WAIT_TIMEOUT;
1033 unsigned long end = (unsigned long) (delay * 1000);
1037 xbt_os_cond_wait(cond, mutex);
1039 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1040 &(mutex->lock), end);
1042 /* lock the threads counter and increment it */
1043 EnterCriticalSection(&cond->waiters_count_lock);
1044 cond->waiters_count++;
1045 LeaveCriticalSection(&cond->waiters_count_lock);
1047 /* unlock the mutex associate with the condition */
1048 LeaveCriticalSection(&mutex->lock);
1049 /* wait for a signal (broadcast or no) */
1051 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1053 switch (wait_result) {
1055 THROWF(timeout_error, GetLastError(),
1056 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1057 cond, mutex, delay);
1059 THROWF(system_error, GetLastError(),
1060 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1063 /* we have a signal lock the condition */
1064 EnterCriticalSection(&cond->waiters_count_lock);
1065 cond->waiters_count--;
1067 /* it's the last waiter or it's a broadcast ? */
1068 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1069 && (cond->waiters_count == 0));
1071 LeaveCriticalSection(&cond->waiters_count_lock);
1073 /* yes it's the last waiter or it's a broadcast
1074 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1078 if (!ResetEvent(cond->events[BROADCAST]))
1079 THROWF(system_error, 0, "ResetEvent failed");
1081 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1082 EnterCriticalSection(&mutex->lock);
1084 /*THROW_UNIMPLEMENTED; */
1087 void xbt_os_cond_signal(xbt_os_cond_t cond)
1091 EnterCriticalSection(&cond->waiters_count_lock);
1092 have_waiters = cond->waiters_count > 0;
1093 LeaveCriticalSection(&cond->waiters_count_lock);
1096 if (!SetEvent(cond->events[SIGNAL]))
1097 THROWF(system_error, 0, "SetEvent failed");
1099 xbt_os_thread_yield();
1102 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1106 EnterCriticalSection(&cond->waiters_count_lock);
1107 have_waiters = cond->waiters_count > 0;
1108 LeaveCriticalSection(&cond->waiters_count_lock);
1111 SetEvent(cond->events[BROADCAST]);
1114 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1121 if (!CloseHandle(cond->events[SIGNAL]))
1124 if (!CloseHandle(cond->events[BROADCAST]))
1127 DeleteCriticalSection(&cond->waiters_count_lock);
1132 THROWF(system_error, 0, "Error while destroying the condition");
1135 typedef struct xbt_os_sem_ {
1138 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1142 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1145 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1149 if (value > INT_MAX)
1150 THROWF(arg_error, value,
1151 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1154 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1156 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1157 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1158 strerror(GetLastError()));
1164 InitializeCriticalSection(&(res->value_lock));
1169 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1172 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1175 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1176 THROWF(system_error, GetLastError(),
1177 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1178 EnterCriticalSection(&(sem->value_lock));
1180 LeaveCriticalSection(&(sem->value_lock));
1183 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1187 double end = timeout + xbt_os_time();
1190 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1193 xbt_os_sem_acquire(sem);
1194 } else { /* timeout can be zero <-> try acquire ) */
1197 seconds = (long) floor(end);
1198 milliseconds = (long) ((end - seconds) * 1000);
1199 milliseconds += (seconds * 1000);
1201 switch (WaitForSingleObject(sem->h, milliseconds)) {
1203 EnterCriticalSection(&(sem->value_lock));
1205 LeaveCriticalSection(&(sem->value_lock));
1209 THROWF(timeout_error, GetLastError(),
1210 "semaphore %p wasn't signaled before timeout (%f)", sem,
1215 THROWF(system_error, GetLastError(),
1216 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1217 strerror(GetLastError()));
1222 void xbt_os_sem_release(xbt_os_sem_t sem)
1225 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1227 if (!ReleaseSemaphore(sem->h, 1, NULL))
1228 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1229 strerror(GetLastError()));
1230 EnterCriticalSection(&(sem->value_lock));
1232 LeaveCriticalSection(&(sem->value_lock));
1235 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1238 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1240 if (!CloseHandle(sem->h))
1241 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1242 strerror(GetLastError()));
1244 DeleteCriticalSection(&(sem->value_lock));
1250 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1253 THROWF(arg_error, EINVAL,
1254 "Cannot get the value of the NULL semaphore");
1256 EnterCriticalSection(&(sem->value_lock));
1257 *svalue = sem->value;
1258 LeaveCriticalSection(&(sem->value_lock));
1265 /** @brief Returns the amount of cores on the current host */
1266 int xbt_os_get_numcores(void) {
1268 SYSTEM_INFO sysinfo;
1269 GetSystemInfo(&sysinfo);
1270 return sysinfo.dwNumberOfProcessors;
1271 #elif defined(__APPLE__) && defined(__MACH__)
1276 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1277 sysctl(nm, 2, &count, &len, NULL, 0);
1281 sysctl(nm, 2, &count, &len, NULL, 0);
1282 if(count < 1) { count = 1; }
1286 return sysconf(_SC_NPROCESSORS_ONLN);
1291 /***** reentrant mutexes *****/
1292 typedef struct xbt_os_rmutex_ {
1293 xbt_os_mutex_t mutex;
1294 xbt_os_thread_t owner;
1296 } s_xbt_os_rmutex_t;
1298 void xbt_os_thread_set_extra_data(void *data)
1300 xbt_os_thread_self()->extra_data = data;
1303 void *xbt_os_thread_get_extra_data(void)
1305 xbt_os_thread_t thread = xbt_os_thread_self();
1307 return xbt_os_thread_self()->extra_data;
1312 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1314 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1315 rmutex->mutex = xbt_os_mutex_init();
1316 rmutex->owner = NULL;
1321 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1323 xbt_os_thread_t self = xbt_os_thread_self();
1326 /* the thread module is not initialized yet */
1327 rmutex->owner = NULL;
1331 if (self != rmutex->owner) {
1332 xbt_os_mutex_acquire(rmutex->mutex);
1333 rmutex->owner = self;
1340 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1342 if (rmutex->owner == NULL) {
1343 /* the thread module was not initialized */
1347 xbt_assert(rmutex->owner == xbt_os_thread_self());
1349 if (--rmutex->count == 0) {
1350 rmutex->owner = NULL;
1351 xbt_os_mutex_release(rmutex->mutex);
1355 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1357 xbt_os_mutex_destroy(rmutex->mutex);