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)
202 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
205 res = pthread_attr_setstacksize(&thread_attr, sz);
207 #ifdef PTHREAD_STACK_MIN
209 /* Invalid size, try again with a multiple of PTHREAD_STACK_MIN. */
210 size_t rem = sz % PTHREAD_STACK_MIN;
211 if (rem != 0 || sz == 0) {
212 size_t sz2 = sz - rem + PTHREAD_STACK_MIN;
213 XBT_DEBUG("pthread_attr_setstacksize failed for %#zx, try again with %#zx",
216 res = pthread_attr_setstacksize(&thread_attr, sz);
222 XBT_WARN("invalid stack size (maybe too big): %#zx", sz);
224 XBT_WARN("unknown error %d in pthread stacksize setting: %#zx", res, sz);
227 const char *xbt_os_thread_name(xbt_os_thread_t t)
232 const char *xbt_os_thread_self_name(void)
234 xbt_os_thread_t me = xbt_os_thread_self();
235 return me ? me->name : "main";
238 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
243 if ((errcode = pthread_join(thread->t, thread_return)))
244 THROWF(system_error, errcode, "pthread_join failed: %s",
246 xbt_os_thread_free_thread_data(thread);
249 void xbt_os_thread_exit(int *retval)
251 pthread_exit(retval);
254 xbt_os_thread_t xbt_os_thread_self(void)
258 if (!thread_mod_inited)
261 res = pthread_getspecific(xbt_self_thread_key);
266 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
269 if ((errcode = pthread_key_create(key, NULL)))
270 THROWF(system_error, errcode, "pthread_key_create failed");
273 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
276 if ((errcode = pthread_setspecific(key, value)))
277 THROWF(system_error, errcode, "pthread_setspecific failed");
280 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
281 return pthread_getspecific(key);
284 void xbt_os_thread_detach(xbt_os_thread_t thread)
286 thread->detached = 1;
287 pthread_detach(thread->t);
291 void xbt_os_thread_yield(void)
296 void xbt_os_thread_cancel(xbt_os_thread_t t)
298 pthread_cancel(t->t);
301 /****** mutex related functions ******/
302 typedef struct xbt_os_mutex_ {
303 /* KEEP IT IN SYNC WITH xbt_thread.c */
310 xbt_os_mutex_t xbt_os_mutex_init(void)
312 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
315 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
316 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
322 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
326 if ((errcode = pthread_mutex_lock(&(mutex->m))))
327 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
328 mutex, strerror(errcode));
332 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
337 xbt_os_mutex_acquire(mutex);
339 } else if (delay == 0) {
340 errcode = pthread_mutex_trylock(&(mutex->m));
346 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
348 THROWF(system_error, errcode,
349 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
356 #ifdef HAVE_MUTEX_TIMEDLOCK
357 struct timespec ts_end;
358 double end = delay + xbt_os_time();
360 ts_end.tv_sec = (time_t) floor(end);
361 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
362 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
364 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
366 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
367 double start = xbt_os_time();
369 errcode = pthread_mutex_trylock(&(mutex->m));
370 if (errcode == EBUSY)
371 xbt_os_thread_yield();
372 } while (errcode == EBUSY && xbt_os_time() - start < delay);
374 if (errcode == EBUSY)
377 #endif /* HAVE_MUTEX_TIMEDLOCK */
384 THROWF(timeout_error, delay,
385 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
388 THROWF(system_error, errcode,
389 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
395 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
399 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
400 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
401 mutex, strerror(errcode));
404 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
411 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
412 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
413 mutex, strerror(errcode));
417 /***** condition related functions *****/
418 typedef struct xbt_os_cond_ {
419 /* KEEP IT IN SYNC WITH xbt_thread.c */
423 xbt_os_cond_t xbt_os_cond_init(void)
425 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
427 if ((errcode = pthread_cond_init(&(res->c), NULL)))
428 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
434 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
437 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
438 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
439 cond, mutex, strerror(errcode));
443 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
447 struct timespec ts_end;
448 double end = delay + xbt_os_time();
451 xbt_os_cond_wait(cond, mutex);
453 ts_end.tv_sec = (time_t) floor(end);
454 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
455 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
458 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
462 THROWF(timeout_error, errcode,
463 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
466 THROWF(system_error, errcode,
467 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
468 delay, strerror(errcode));
473 void xbt_os_cond_signal(xbt_os_cond_t cond)
476 if ((errcode = pthread_cond_signal(&(cond->c))))
477 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
478 cond, strerror(errcode));
481 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
484 if ((errcode = pthread_cond_broadcast(&(cond->c))))
485 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
486 cond, strerror(errcode));
489 void xbt_os_cond_destroy(xbt_os_cond_t cond)
496 if ((errcode = pthread_cond_destroy(&(cond->c))))
497 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
498 cond, strerror(errcode));
502 void *xbt_os_thread_getparam(void)
504 xbt_os_thread_t t = xbt_os_thread_self();
505 return t ? t->param : NULL;
508 typedef struct xbt_os_sem_ {
509 #ifndef HAVE_SEM_INIT
517 #define SEM_FAILED (-1)
520 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
522 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
524 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
525 * Any attempt to use it leads to ENOSYS (function not implemented).
526 * If such a prehistoric system is detected, do the job with sem_open instead
529 if (sem_init(&(res->s), 0, value) != 0)
530 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
533 #else /* damn, no sem_init(). Reimplement it */
535 xbt_os_mutex_acquire(next_sem_ID_lock);
536 res->name = bprintf("/%d", ++next_sem_ID);
537 xbt_os_mutex_release(next_sem_ID_lock);
539 res->ps = sem_open(res->name, O_CREAT, 0644, value);
540 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
541 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
542 res->name[13] = '\0';
543 res->ps = sem_open(res->name, O_CREAT, 0644, value);
545 if ((res->ps == (sem_t *) SEM_FAILED))
546 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
548 /* Remove the name from the semaphore namespace: we never join on it */
549 if (sem_unlink(res->name) < 0)
550 THROWF(system_error, errno, "sem_unlink() failed: %s",
558 void xbt_os_sem_acquire(xbt_os_sem_t sem)
561 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
562 if (sem_wait(sem->ps) < 0)
563 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
566 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
571 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
574 xbt_os_sem_acquire(sem);
575 } else if (delay == 0) {
576 errcode = sem_trywait(sem->ps);
582 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
584 THROWF(system_error, errcode,
585 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
591 struct timespec ts_end;
592 double end = delay + xbt_os_time();
594 ts_end.tv_sec = (time_t) floor(end);
595 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
596 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
597 errcode = sem_timedwait(sem->s, &ts_end);
599 #else /* Okay, reimplement this function then */
600 double start = xbt_os_time();
602 errcode = sem_trywait(sem->ps);
603 if (errcode == EBUSY)
604 xbt_os_thread_yield();
605 } while (errcode == EBUSY && xbt_os_time() - start < delay);
607 if (errcode == EBUSY)
616 THROWF(timeout_error, delay,
617 "semaphore %p wasn't signaled before timeout (%f)", sem,
621 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
622 delay, strerror(errcode));
627 void xbt_os_sem_release(xbt_os_sem_t sem)
630 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
632 if (sem_post(sem->ps) < 0)
633 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
636 void xbt_os_sem_destroy(xbt_os_sem_t sem)
639 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
642 if (sem_destroy(sem->ps) < 0)
643 THROWF(system_error, errno, "sem_destroy() failed: %s",
646 if (sem_close(sem->ps) < 0)
647 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
654 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
657 THROWF(arg_error, EINVAL,
658 "Cannot get the value of the NULL semaphore");
660 if (sem_getvalue(&(sem->s), svalue) < 0)
661 THROWF(system_error, errno, "sem_getvalue() failed: %s",
665 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
667 #elif defined(_XBT_WIN32)
671 typedef struct xbt_os_thread_ {
673 HANDLE handle; /* the win thread handle */
674 unsigned long id; /* the win thread id */
675 pvoid_f_pvoid_t start_routine;
680 /* so we can specify the size of the stack of the threads */
681 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
682 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
685 /* the default size of the stack of the threads (in bytes)*/
686 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
687 static int stack_size=0;
688 /* key to the TLS containing the xbt_os_thread_t structure */
689 static unsigned long xbt_self_thread_key;
691 void xbt_os_thread_mod_preinit(void)
693 xbt_self_thread_key = TlsAlloc();
696 void xbt_os_thread_mod_postexit(void)
699 if (!TlsFree(xbt_self_thread_key))
700 THROWF(system_error, (int) GetLastError(),
701 "TlsFree() failed to cleanup the thread submodule");
704 int xbt_os_thread_atfork(void (*prepare)(void),
705 void (*parent)(void), void (*child)(void))
710 static DWORD WINAPI wrapper_start_routine(void *s)
712 xbt_os_thread_t t = (xbt_os_thread_t) s;
715 if (!TlsSetValue(xbt_self_thread_key, t))
716 THROWF(system_error, (int) GetLastError(),
717 "TlsSetValue of data describing the created thread failed");
719 rv = (DWORD *) ((t->start_routine) (t->param));
726 xbt_os_thread_t xbt_os_thread_create(const char *name,
727 pvoid_f_pvoid_t start_routine,
732 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
734 t->name = xbt_strdup(name);
735 t->start_routine = start_routine;
737 t->extra_data = extra_data;
738 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
739 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
740 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
744 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
750 void xbt_os_thread_setstacksize(int size)
755 const char *xbt_os_thread_name(xbt_os_thread_t t)
760 const char *xbt_os_thread_self_name(void)
762 xbt_os_thread_t t = xbt_os_thread_self();
763 return t ? t->name : "main";
766 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
769 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
770 THROWF(system_error, (int) GetLastError(),
771 "WaitForSingleObject failed");
775 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
776 THROWF(system_error, (int) GetLastError(),
777 "GetExitCodeThread failed");
780 CloseHandle(thread->handle);
787 void xbt_os_thread_exit(int *retval)
795 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
800 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
802 if (!TlsSetValue(key, value))
803 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
806 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
807 return TlsGetValue(key);
810 void xbt_os_thread_detach(xbt_os_thread_t thread)
816 xbt_os_thread_t xbt_os_thread_self(void)
818 return TlsGetValue(xbt_self_thread_key);
821 void *xbt_os_thread_getparam(void)
823 xbt_os_thread_t t = xbt_os_thread_self();
828 void xbt_os_thread_yield(void)
833 void xbt_os_thread_cancel(xbt_os_thread_t t)
835 if (!TerminateThread(t->handle, 0))
836 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
839 /****** mutex related functions ******/
840 typedef struct xbt_os_mutex_ {
841 /* KEEP IT IN SYNC WITH xbt_thread.c */
842 CRITICAL_SECTION lock;
845 xbt_os_mutex_t xbt_os_mutex_init(void)
847 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
849 /* initialize the critical section object */
850 InitializeCriticalSection(&(res->lock));
855 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
857 EnterCriticalSection(&mutex->lock);
860 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
865 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
868 LeaveCriticalSection(&mutex->lock);
872 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
878 DeleteCriticalSection(&mutex->lock);
882 /***** condition related functions *****/
883 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
889 typedef struct xbt_os_cond_ {
890 /* KEEP IT IN SYNC WITH xbt_thread.c */
891 HANDLE events[MAX_EVENTS];
893 unsigned int waiters_count; /* the number of waiters */
894 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
897 xbt_os_cond_t xbt_os_cond_init(void)
900 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
902 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
904 /* initialize the critical section object */
905 InitializeCriticalSection(&res->waiters_count_lock);
907 res->waiters_count = 0;
909 /* Create an auto-reset event */
910 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
912 if (!res->events[SIGNAL]) {
913 DeleteCriticalSection(&res->waiters_count_lock);
915 THROWF(system_error, 0, "CreateEvent failed for the signals");
918 /* Create a manual-reset event. */
919 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
921 if (!res->events[BROADCAST]) {
923 DeleteCriticalSection(&res->waiters_count_lock);
924 CloseHandle(res->events[SIGNAL]);
926 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
932 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
935 unsigned long wait_result;
938 /* lock the threads counter and increment it */
939 EnterCriticalSection(&cond->waiters_count_lock);
940 cond->waiters_count++;
941 LeaveCriticalSection(&cond->waiters_count_lock);
943 /* unlock the mutex associate with the condition */
944 LeaveCriticalSection(&mutex->lock);
946 /* wait for a signal (broadcast or no) */
947 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
949 if (wait_result == WAIT_FAILED)
950 THROWF(system_error, 0,
951 "WaitForMultipleObjects failed, so we cannot wait on the condition");
953 /* we have a signal lock the condition */
954 EnterCriticalSection(&cond->waiters_count_lock);
955 cond->waiters_count--;
957 /* it's the last waiter or it's a broadcast ? */
958 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
959 && (cond->waiters_count == 0));
961 LeaveCriticalSection(&cond->waiters_count_lock);
963 /* yes it's the last waiter or it's a broadcast
964 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
968 if (!ResetEvent(cond->events[BROADCAST]))
969 THROWF(system_error, 0, "ResetEvent failed");
971 /* relock the mutex associated with the condition in accordance with the posix thread specification */
972 EnterCriticalSection(&mutex->lock);
975 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
979 unsigned long wait_result = WAIT_TIMEOUT;
981 unsigned long end = (unsigned long) (delay * 1000);
985 xbt_os_cond_wait(cond, mutex);
987 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
988 &(mutex->lock), end);
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);
997 /* wait for a signal (broadcast or no) */
999 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1001 switch (wait_result) {
1003 THROWF(timeout_error, GetLastError(),
1004 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1005 cond, mutex, delay);
1007 THROWF(system_error, GetLastError(),
1008 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1011 /* we have a signal lock the condition */
1012 EnterCriticalSection(&cond->waiters_count_lock);
1013 cond->waiters_count--;
1015 /* it's the last waiter or it's a broadcast ? */
1016 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1017 && (cond->waiters_count == 0));
1019 LeaveCriticalSection(&cond->waiters_count_lock);
1021 /* yes it's the last waiter or it's a broadcast
1022 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1026 if (!ResetEvent(cond->events[BROADCAST]))
1027 THROWF(system_error, 0, "ResetEvent failed");
1029 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1030 EnterCriticalSection(&mutex->lock);
1032 /*THROW_UNIMPLEMENTED; */
1035 void xbt_os_cond_signal(xbt_os_cond_t cond)
1039 EnterCriticalSection(&cond->waiters_count_lock);
1040 have_waiters = cond->waiters_count > 0;
1041 LeaveCriticalSection(&cond->waiters_count_lock);
1044 if (!SetEvent(cond->events[SIGNAL]))
1045 THROWF(system_error, 0, "SetEvent failed");
1047 xbt_os_thread_yield();
1050 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1054 EnterCriticalSection(&cond->waiters_count_lock);
1055 have_waiters = cond->waiters_count > 0;
1056 LeaveCriticalSection(&cond->waiters_count_lock);
1059 SetEvent(cond->events[BROADCAST]);
1062 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1069 if (!CloseHandle(cond->events[SIGNAL]))
1072 if (!CloseHandle(cond->events[BROADCAST]))
1075 DeleteCriticalSection(&cond->waiters_count_lock);
1080 THROWF(system_error, 0, "Error while destroying the condition");
1083 typedef struct xbt_os_sem_ {
1086 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1090 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1093 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1097 if (value > INT_MAX)
1098 THROWF(arg_error, value,
1099 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1102 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1104 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1105 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1106 strerror(GetLastError()));
1112 InitializeCriticalSection(&(res->value_lock));
1117 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1120 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1123 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1124 THROWF(system_error, GetLastError(),
1125 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1126 EnterCriticalSection(&(sem->value_lock));
1128 LeaveCriticalSection(&(sem->value_lock));
1131 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1135 double end = timeout + xbt_os_time();
1138 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1141 xbt_os_sem_acquire(sem);
1142 } else { /* timeout can be zero <-> try acquire ) */
1145 seconds = (long) floor(end);
1146 milliseconds = (long) ((end - seconds) * 1000);
1147 milliseconds += (seconds * 1000);
1149 switch (WaitForSingleObject(sem->h, milliseconds)) {
1151 EnterCriticalSection(&(sem->value_lock));
1153 LeaveCriticalSection(&(sem->value_lock));
1157 THROWF(timeout_error, GetLastError(),
1158 "semaphore %p wasn't signaled before timeout (%f)", sem,
1163 THROWF(system_error, GetLastError(),
1164 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1165 strerror(GetLastError()));
1170 void xbt_os_sem_release(xbt_os_sem_t sem)
1173 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1175 if (!ReleaseSemaphore(sem->h, 1, NULL))
1176 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1177 strerror(GetLastError()));
1178 EnterCriticalSection(&(sem->value_lock));
1180 LeaveCriticalSection(&(sem->value_lock));
1183 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1186 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1188 if (!CloseHandle(sem->h))
1189 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1190 strerror(GetLastError()));
1192 DeleteCriticalSection(&(sem->value_lock));
1198 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1201 THROWF(arg_error, EINVAL,
1202 "Cannot get the value of the NULL semaphore");
1204 EnterCriticalSection(&(sem->value_lock));
1205 *svalue = sem->value;
1206 LeaveCriticalSection(&(sem->value_lock));
1213 /** @brief Returns the amount of cores on the current host */
1214 int xbt_os_get_numcores(void) {
1216 SYSTEM_INFO sysinfo;
1217 GetSystemInfo(&sysinfo);
1218 return sysinfo.dwNumberOfProcessors;
1224 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1225 sysctl(nm, 2, &count, &len, NULL, 0);
1229 sysctl(nm, 2, &count, &len, NULL, 0);
1230 if(count < 1) { count = 1; }
1234 return sysconf(_SC_NPROCESSORS_ONLN);
1239 /***** reentrant mutexes *****/
1240 typedef struct xbt_os_rmutex_ {
1241 xbt_os_mutex_t mutex;
1242 xbt_os_thread_t owner;
1244 } s_xbt_os_rmutex_t;
1246 void xbt_os_thread_set_extra_data(void *data)
1248 xbt_os_thread_self()->extra_data = data;
1251 void *xbt_os_thread_get_extra_data(void)
1253 xbt_os_thread_t self = xbt_os_thread_self();
1254 return self? self->extra_data : NULL;
1257 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1259 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1260 rmutex->mutex = xbt_os_mutex_init();
1261 rmutex->owner = NULL;
1266 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1268 xbt_os_thread_t self = xbt_os_thread_self();
1271 /* the thread module is not initialized yet */
1272 rmutex->owner = NULL;
1276 if (self != rmutex->owner) {
1277 xbt_os_mutex_acquire(rmutex->mutex);
1278 rmutex->owner = self;
1285 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1287 if (rmutex->owner == NULL) {
1288 /* the thread module was not initialized */
1292 xbt_assert(rmutex->owner == xbt_os_thread_self());
1294 if (--rmutex->count == 0) {
1295 rmutex->owner = NULL;
1296 xbt_os_mutex_release(rmutex->mutex);
1300 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1302 xbt_os_mutex_destroy(rmutex->mutex);