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, 2008, 2009, 2010. 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 "gras_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 ************************************ */
26 #include <semaphore.h>
28 #ifdef HAVE_MUTEX_TIMEDLOCK
29 /* redefine the function header since we fail to get this from system headers on amd (at least) */
30 int pthread_mutex_timedlock(pthread_mutex_t * mutex,
31 const struct timespec *abs_timeout);
35 /* use named sempahore when sem_init() does not work */
37 static int next_sem_ID = 0;
38 static xbt_os_mutex_t next_sem_ID_lock;
41 typedef struct xbt_os_thread_ {
46 pvoid_f_pvoid_t start_routine;
47 xbt_running_ctx_t *running_ctx;
50 static xbt_os_thread_t main_thread = NULL;
52 /* thread-specific data containing the xbt_os_thread_t structure */
53 static pthread_key_t xbt_self_thread_key;
54 static int thread_mod_inited = 0;
56 /* attribute structure to handle pthread stack size changing */
57 //FIXME: find where to put this
58 static pthread_attr_t attr;
59 static int thread_attr_inited = 0;
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");
109 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
110 __xbt_ex_terminate = _os_thread_ex_terminate;
112 thread_mod_inited = 1;
114 #ifndef HAVE_SEM_INIT
115 next_sem_ID_lock = xbt_os_mutex_init();
120 void xbt_os_thread_mod_postexit(void)
122 /* FIXME: don't try to free our key on shutdown.
123 Valgrind detects no leak if we don't, and whine if we try to */
126 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
127 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
128 free(main_thread->running_ctx);
131 thread_mod_inited = 0;
132 #ifndef HAVE_SEM_INIT
133 xbt_os_mutex_destroy(next_sem_ID_lock);
136 /* Restore the default exception setup */
137 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
138 __xbt_ex_terminate = &__xbt_ex_terminate_default;
141 /* this function is critical to tesh+mmalloc, don't mess with it */
142 int xbt_os_thread_atfork(void (*prepare)(void),
143 void (*parent)(void), void (*child)(void))
146 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
148 return pthread_atfork(prepare, parent, child);
152 static void *wrapper_start_routine(void *s)
154 xbt_os_thread_t t = s;
157 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
158 THROWF(system_error, errcode,
159 "pthread_setspecific failed for xbt_self_thread_key");
161 void *res = t->start_routine(t->param);
163 xbt_os_thread_free_thread_data(t);
168 xbt_os_thread_t xbt_os_thread_create(const char *name,
169 pvoid_f_pvoid_t start_routine,
175 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
176 res_thread->detached = 0;
177 res_thread->name = xbt_strdup(name);
178 res_thread->start_routine = start_routine;
179 res_thread->param = param;
180 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
181 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
182 res_thread->extra_data = extra_data;
184 if ((errcode = pthread_create(&(res_thread->t), thread_attr_inited!=0? &attr: NULL,
185 wrapper_start_routine, res_thread)))
186 THROWF(system_error, errcode,
187 "pthread_create failed: %s", strerror(errcode));
195 void xbt_os_thread_setstacksize(int stack_size)
197 pthread_attr_init(&attr);
198 pthread_attr_setstacksize (&attr, stack_size);
199 thread_attr_inited=1;
202 const char *xbt_os_thread_name(xbt_os_thread_t t)
207 const char *xbt_os_thread_self_name(void)
209 xbt_os_thread_t me = xbt_os_thread_self();
210 return me ? me->name : "main";
213 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
218 if ((errcode = pthread_join(thread->t, thread_return)))
219 THROWF(system_error, errcode, "pthread_join failed: %s",
221 xbt_os_thread_free_thread_data(thread);
224 void xbt_os_thread_exit(int *retval)
226 pthread_exit(retval);
229 xbt_os_thread_t xbt_os_thread_self(void)
233 if (!thread_mod_inited)
236 res = pthread_getspecific(xbt_self_thread_key);
241 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
244 if ((errcode = pthread_key_create(key, NULL)))
245 THROWF(system_error, errcode, "pthread_key_create failed");
248 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
251 if ((errcode = pthread_setspecific(key, value)))
252 THROWF(system_error, errcode, "pthread_setspecific failed");
255 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
256 return pthread_getspecific(key);
259 void xbt_os_thread_detach(xbt_os_thread_t thread)
261 thread->detached = 1;
262 pthread_detach(thread->t);
266 void xbt_os_thread_yield(void)
271 void xbt_os_thread_cancel(xbt_os_thread_t t)
273 pthread_cancel(t->t);
276 /****** mutex related functions ******/
277 typedef struct xbt_os_mutex_ {
278 /* KEEP IT IN SYNC WITH xbt_thread.c */
285 xbt_os_mutex_t xbt_os_mutex_init(void)
287 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
290 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
291 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
297 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
301 if ((errcode = pthread_mutex_lock(&(mutex->m))))
302 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
303 mutex, strerror(errcode));
307 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
312 xbt_os_mutex_acquire(mutex);
314 } else if (delay == 0) {
315 errcode = pthread_mutex_trylock(&(mutex->m));
321 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
323 THROWF(system_error, errcode,
324 "xbt_mutex_timedacquire(%p) failed: %s", mutex,
331 #ifdef HAVE_MUTEX_TIMEDLOCK
332 struct timespec ts_end;
333 double end = delay + xbt_os_time();
335 ts_end.tv_sec = (time_t) floor(end);
336 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
337 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
339 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
341 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
342 double start = xbt_os_time();
344 errcode = pthread_mutex_trylock(&(mutex->m));
345 if (errcode == EBUSY)
346 xbt_os_thread_yield();
347 } while (errcode == EBUSY && xbt_os_time() - start < delay);
349 if (errcode == EBUSY)
352 #endif /* HAVE_MUTEX_TIMEDLOCK */
359 THROWF(timeout_error, delay,
360 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
363 THROWF(system_error, errcode,
364 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
370 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
374 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
375 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
376 mutex, strerror(errcode));
379 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
386 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
387 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
388 mutex, strerror(errcode));
392 /***** condition related functions *****/
393 typedef struct xbt_os_cond_ {
394 /* KEEP IT IN SYNC WITH xbt_thread.c */
398 xbt_os_cond_t xbt_os_cond_init(void)
400 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
402 if ((errcode = pthread_cond_init(&(res->c), NULL)))
403 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
409 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
412 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
413 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
414 cond, mutex, strerror(errcode));
418 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
422 struct timespec ts_end;
423 double end = delay + xbt_os_time();
426 xbt_os_cond_wait(cond, mutex);
428 ts_end.tv_sec = (time_t) floor(end);
429 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
430 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
433 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
437 THROWF(timeout_error, errcode,
438 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
441 THROWF(system_error, errcode,
442 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
443 delay, strerror(errcode));
448 void xbt_os_cond_signal(xbt_os_cond_t cond)
451 if ((errcode = pthread_cond_signal(&(cond->c))))
452 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
453 cond, strerror(errcode));
456 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
459 if ((errcode = pthread_cond_broadcast(&(cond->c))))
460 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
461 cond, strerror(errcode));
464 void xbt_os_cond_destroy(xbt_os_cond_t cond)
471 if ((errcode = pthread_cond_destroy(&(cond->c))))
472 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
473 cond, strerror(errcode));
477 void *xbt_os_thread_getparam(void)
479 xbt_os_thread_t t = xbt_os_thread_self();
480 return t ? t->param : NULL;
483 typedef struct xbt_os_sem_ {
484 #ifndef HAVE_SEM_INIT
492 #define SEM_FAILED (-1)
495 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
497 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
499 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
500 * Any attempt to use it leads to ENOSYS (function not implemented).
501 * If such a prehistoric system is detected, do the job with sem_open instead
504 if (sem_init(&(res->s), 0, value) != 0)
505 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
508 #else /* damn, no sem_init(). Reimplement it */
510 xbt_os_mutex_acquire(next_sem_ID_lock);
511 res->name = bprintf("/%d", ++next_sem_ID);
512 xbt_os_mutex_release(next_sem_ID_lock);
514 res->ps = sem_open(res->name, O_CREAT, 0644, value);
515 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
516 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
517 res->name[13] = '\0';
518 res->ps = sem_open(res->name, O_CREAT, 0644, value);
520 if ((res->ps == (sem_t *) SEM_FAILED))
521 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
523 /* Remove the name from the semaphore namespace: we never join on it */
524 if (sem_unlink(res->name) < 0)
525 THROWF(system_error, errno, "sem_unlink() failed: %s",
533 void xbt_os_sem_acquire(xbt_os_sem_t sem)
536 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
537 if (sem_wait(sem->ps) < 0)
538 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
541 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
546 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
549 xbt_os_sem_acquire(sem);
550 } else if (delay == 0) {
551 errcode = sem_trywait(sem->ps);
557 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
559 THROWF(system_error, errcode,
560 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
566 struct timespec ts_end;
567 double end = delay + xbt_os_time();
569 ts_end.tv_sec = (time_t) floor(end);
570 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
571 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
572 errcode = sem_timedwait(sem->s, &ts_end);
574 #else /* Okay, reimplement this function then */
575 double start = xbt_os_time();
577 errcode = sem_trywait(sem->ps);
578 if (errcode == EBUSY)
579 xbt_os_thread_yield();
580 } while (errcode == EBUSY && xbt_os_time() - start < delay);
582 if (errcode == EBUSY)
591 THROWF(timeout_error, delay,
592 "semaphore %p wasn't signaled before timeout (%f)", sem,
596 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
597 delay, strerror(errcode));
602 void xbt_os_sem_release(xbt_os_sem_t sem)
605 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
607 if (sem_post(sem->ps) < 0)
608 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
611 void xbt_os_sem_destroy(xbt_os_sem_t sem)
614 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
617 if (sem_destroy(sem->ps) < 0)
618 THROWF(system_error, errno, "sem_destroy() failed: %s",
621 if (sem_close(sem->ps) < 0)
622 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
629 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
632 THROWF(arg_error, EINVAL,
633 "Cannot get the value of the NULL semaphore");
635 if (sem_getvalue(&(sem->s), svalue) < 0)
636 THROWF(system_error, errno, "sem_getvalue() failed: %s",
640 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
642 #elif defined(_XBT_WIN32)
646 typedef struct xbt_os_thread_ {
648 HANDLE handle; /* the win thread handle */
649 unsigned long id; /* the win thread id */
650 pvoid_f_pvoid_t start_routine;
655 /* so we can specify the size of the stack of the threads */
656 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
657 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
660 /* the default size of the stack of the threads (in bytes)*/
661 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
662 static int stack_size=0;
663 /* key to the TLS containing the xbt_os_thread_t structure */
664 static unsigned long xbt_self_thread_key;
666 void xbt_os_thread_mod_preinit(void)
668 xbt_self_thread_key = TlsAlloc();
671 void xbt_os_thread_mod_postexit(void)
674 if (!TlsFree(xbt_self_thread_key))
675 THROWF(system_error, (int) GetLastError(),
676 "TlsFree() failed to cleanup the thread submodule");
679 int xbt_os_thread_atfork(void (*prepare)(void),
680 void (*parent)(void), void (*child)(void))
685 static DWORD WINAPI wrapper_start_routine(void *s)
687 xbt_os_thread_t t = (xbt_os_thread_t) s;
690 if (!TlsSetValue(xbt_self_thread_key, t))
691 THROWF(system_error, (int) GetLastError(),
692 "TlsSetValue of data describing the created thread failed");
694 rv = (DWORD *) ((t->start_routine) (t->param));
701 xbt_os_thread_t xbt_os_thread_create(const char *name,
702 pvoid_f_pvoid_t start_routine,
707 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
709 t->name = xbt_strdup(name);
710 t->start_routine = start_routine;
712 t->extra_data = extra_data;
713 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
714 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
715 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
719 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
725 void xbt_os_thread_setstacksize(int size)
730 const char *xbt_os_thread_name(xbt_os_thread_t t)
735 const char *xbt_os_thread_self_name(void)
737 xbt_os_thread_t t = xbt_os_thread_self();
738 return t ? t->name : "main";
741 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
744 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
745 THROWF(system_error, (int) GetLastError(),
746 "WaitForSingleObject failed");
750 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
751 THROWF(system_error, (int) GetLastError(),
752 "GetExitCodeThread failed");
755 CloseHandle(thread->handle);
762 void xbt_os_thread_exit(int *retval)
770 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
775 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
777 if (!TlsSetValue(key, value))
778 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
781 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
782 return TlsGetValue(key);
785 void xbt_os_thread_detach(xbt_os_thread_t thread)
791 xbt_os_thread_t xbt_os_thread_self(void)
793 return TlsGetValue(xbt_self_thread_key);
796 void *xbt_os_thread_getparam(void)
798 xbt_os_thread_t t = xbt_os_thread_self();
803 void xbt_os_thread_yield(void)
808 void xbt_os_thread_cancel(xbt_os_thread_t t)
810 if (!TerminateThread(t->handle, 0))
811 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
814 /****** mutex related functions ******/
815 typedef struct xbt_os_mutex_ {
816 /* KEEP IT IN SYNC WITH xbt_thread.c */
817 CRITICAL_SECTION lock;
820 xbt_os_mutex_t xbt_os_mutex_init(void)
822 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
824 /* initialize the critical section object */
825 InitializeCriticalSection(&(res->lock));
830 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
832 EnterCriticalSection(&mutex->lock);
835 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
840 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
843 LeaveCriticalSection(&mutex->lock);
847 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
853 DeleteCriticalSection(&mutex->lock);
857 /***** condition related functions *****/
858 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
864 typedef struct xbt_os_cond_ {
865 /* KEEP IT IN SYNC WITH xbt_thread.c */
866 HANDLE events[MAX_EVENTS];
868 unsigned int waiters_count; /* the number of waiters */
869 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
872 xbt_os_cond_t xbt_os_cond_init(void)
875 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
877 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
879 /* initialize the critical section object */
880 InitializeCriticalSection(&res->waiters_count_lock);
882 res->waiters_count = 0;
884 /* Create an auto-reset event */
885 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
887 if (!res->events[SIGNAL]) {
888 DeleteCriticalSection(&res->waiters_count_lock);
890 THROWF(system_error, 0, "CreateEvent failed for the signals");
893 /* Create a manual-reset event. */
894 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
896 if (!res->events[BROADCAST]) {
898 DeleteCriticalSection(&res->waiters_count_lock);
899 CloseHandle(res->events[SIGNAL]);
901 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
907 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
910 unsigned long wait_result;
913 /* lock the threads counter and increment it */
914 EnterCriticalSection(&cond->waiters_count_lock);
915 cond->waiters_count++;
916 LeaveCriticalSection(&cond->waiters_count_lock);
918 /* unlock the mutex associate with the condition */
919 LeaveCriticalSection(&mutex->lock);
921 /* wait for a signal (broadcast or no) */
922 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
924 if (wait_result == WAIT_FAILED)
925 THROWF(system_error, 0,
926 "WaitForMultipleObjects failed, so we cannot wait on the condition");
928 /* we have a signal lock the condition */
929 EnterCriticalSection(&cond->waiters_count_lock);
930 cond->waiters_count--;
932 /* it's the last waiter or it's a broadcast ? */
933 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
934 && (cond->waiters_count == 0));
936 LeaveCriticalSection(&cond->waiters_count_lock);
938 /* yes it's the last waiter or it's a broadcast
939 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
943 if (!ResetEvent(cond->events[BROADCAST]))
944 THROWF(system_error, 0, "ResetEvent failed");
946 /* relock the mutex associated with the condition in accordance with the posix thread specification */
947 EnterCriticalSection(&mutex->lock);
950 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
954 unsigned long wait_result = WAIT_TIMEOUT;
956 unsigned long end = (unsigned long) (delay * 1000);
960 xbt_os_cond_wait(cond, mutex);
962 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
963 &(mutex->lock), end);
965 /* lock the threads counter and increment it */
966 EnterCriticalSection(&cond->waiters_count_lock);
967 cond->waiters_count++;
968 LeaveCriticalSection(&cond->waiters_count_lock);
970 /* unlock the mutex associate with the condition */
971 LeaveCriticalSection(&mutex->lock);
972 /* wait for a signal (broadcast or no) */
974 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
976 switch (wait_result) {
978 THROWF(timeout_error, GetLastError(),
979 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
982 THROWF(system_error, GetLastError(),
983 "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);
1007 /*THROW_UNIMPLEMENTED; */
1010 void xbt_os_cond_signal(xbt_os_cond_t cond)
1014 EnterCriticalSection(&cond->waiters_count_lock);
1015 have_waiters = cond->waiters_count > 0;
1016 LeaveCriticalSection(&cond->waiters_count_lock);
1019 if (!SetEvent(cond->events[SIGNAL]))
1020 THROWF(system_error, 0, "SetEvent failed");
1022 xbt_os_thread_yield();
1025 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1029 EnterCriticalSection(&cond->waiters_count_lock);
1030 have_waiters = cond->waiters_count > 0;
1031 LeaveCriticalSection(&cond->waiters_count_lock);
1034 SetEvent(cond->events[BROADCAST]);
1037 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1044 if (!CloseHandle(cond->events[SIGNAL]))
1047 if (!CloseHandle(cond->events[BROADCAST]))
1050 DeleteCriticalSection(&cond->waiters_count_lock);
1055 THROWF(system_error, 0, "Error while destroying the condition");
1058 typedef struct xbt_os_sem_ {
1061 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1065 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1068 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1072 if (value > INT_MAX)
1073 THROWF(arg_error, value,
1074 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1077 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1079 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1080 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1081 strerror(GetLastError()));
1087 InitializeCriticalSection(&(res->value_lock));
1092 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1095 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1098 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1099 THROWF(system_error, GetLastError(),
1100 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1101 EnterCriticalSection(&(sem->value_lock));
1103 LeaveCriticalSection(&(sem->value_lock));
1106 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1110 double end = timeout + xbt_os_time();
1113 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1116 xbt_os_sem_acquire(sem);
1117 } else { /* timeout can be zero <-> try acquire ) */
1120 seconds = (long) floor(end);
1121 milliseconds = (long) ((end - seconds) * 1000);
1122 milliseconds += (seconds * 1000);
1124 switch (WaitForSingleObject(sem->h, milliseconds)) {
1126 EnterCriticalSection(&(sem->value_lock));
1128 LeaveCriticalSection(&(sem->value_lock));
1132 THROWF(timeout_error, GetLastError(),
1133 "semaphore %p wasn't signaled before timeout (%f)", sem,
1138 THROWF(system_error, GetLastError(),
1139 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1140 strerror(GetLastError()));
1145 void xbt_os_sem_release(xbt_os_sem_t sem)
1148 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1150 if (!ReleaseSemaphore(sem->h, 1, NULL))
1151 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1152 strerror(GetLastError()));
1153 EnterCriticalSection(&(sem->value_lock));
1155 LeaveCriticalSection(&(sem->value_lock));
1158 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1161 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1163 if (!CloseHandle(sem->h))
1164 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1165 strerror(GetLastError()));
1167 DeleteCriticalSection(&(sem->value_lock));
1173 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1176 THROWF(arg_error, EINVAL,
1177 "Cannot get the value of the NULL semaphore");
1179 EnterCriticalSection(&(sem->value_lock));
1180 *svalue = sem->value;
1181 LeaveCriticalSection(&(sem->value_lock));
1188 /** @brief Returns the amount of cores on the current host */
1189 int xbt_os_get_numcores(void) {
1191 SYSTEM_INFO sysinfo;
1192 GetSystemInfo(&sysinfo);
1193 return sysinfo.dwNumberOfProcessors;
1199 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1200 sysctl(nm, 2, &count, &len, NULL, 0);
1204 sysctl(nm, 2, &count, &len, NULL, 0);
1205 if(count < 1) { count = 1; }
1209 return sysconf(_SC_NPROCESSORS_ONLN);
1214 /***** reentrant mutexes *****/
1215 typedef struct xbt_os_rmutex_ {
1216 xbt_os_mutex_t mutex;
1217 xbt_os_thread_t owner;
1219 } s_xbt_os_rmutex_t;
1221 void xbt_os_thread_set_extra_data(void *data)
1223 xbt_os_thread_self()->extra_data = data;
1226 void *xbt_os_thread_get_extra_data(void)
1228 return xbt_os_thread_self()->extra_data;
1231 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1233 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1234 rmutex->mutex = xbt_os_mutex_init();
1235 rmutex->owner = NULL;
1240 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1242 xbt_os_thread_t self = xbt_os_thread_self();
1245 /* the thread module is not initialized yet */
1246 rmutex->owner = NULL;
1250 if (self != rmutex->owner) {
1251 xbt_os_mutex_acquire(rmutex->mutex);
1252 rmutex->owner = self;
1259 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1261 if (rmutex->owner == NULL) {
1262 /* the thread module was not initialized */
1266 xbt_assert(rmutex->owner == xbt_os_thread_self());
1268 if (--rmutex->count == 0) {
1269 rmutex->owner = NULL;
1270 xbt_os_mutex_release(rmutex->mutex);
1274 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1276 xbt_os_mutex_destroy(rmutex->mutex);