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-2013. 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 /* attribute structure to handle pthread stack size changing */
58 //FIXME: find where to put this
59 static pthread_attr_t attr;
60 static int thread_attr_inited = 0;
62 /* frees the xbt_os_thread_t corresponding to the current thread */
63 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
65 if (thread == main_thread) /* just killed main thread */
68 free(thread->running_ctx);
73 /* callback: context fetching */
74 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
76 return xbt_os_thread_self()->running_ctx;
79 /* callback: termination */
80 static void _os_thread_ex_terminate(xbt_ex_t * e)
84 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
87 void xbt_os_thread_mod_preinit(void)
91 if (thread_mod_inited)
94 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
95 THROWF(system_error, errcode,
96 "pthread_key_create failed for xbt_self_thread_key");
98 main_thread = xbt_new(s_xbt_os_thread_t, 1);
99 main_thread->name = (char *) "main";
100 main_thread->start_routine = NULL;
101 main_thread->param = NULL;
102 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
103 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
105 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
106 THROWF(system_error, errcode,
107 "pthread_setspecific failed for xbt_self_thread_key");
110 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
111 __xbt_ex_terminate = _os_thread_ex_terminate;
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_inited!=0? &attr: NULL,
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 pthread_attr_init(&attr);
206 res = pthread_attr_setstacksize(&attr, sz);
208 #ifdef PTHREAD_STACK_MIN
210 /* Invalid size, try again with a multiple of PTHREAD_STACK_MIN. */
211 size_t rem = sz % PTHREAD_STACK_MIN;
212 if (rem != 0 || sz == 0) {
213 size_t sz2 = sz - rem + PTHREAD_STACK_MIN;
214 XBT_DEBUG("pthread_attr_setstacksize failed for %#zx, try again with %#zx",
217 res = pthread_attr_setstacksize(&attr, sz);
223 XBT_WARN("invalid stack size (maybe too big): %#zx", sz);
225 XBT_WARN("unknown error %d in pthread stacksize setting: %#zx", res, sz);
226 thread_attr_inited = 1;
229 const char *xbt_os_thread_name(xbt_os_thread_t t)
234 const char *xbt_os_thread_self_name(void)
236 xbt_os_thread_t me = xbt_os_thread_self();
237 return me ? me->name : "main";
240 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
245 if ((errcode = pthread_join(thread->t, thread_return)))
246 THROWF(system_error, errcode, "pthread_join failed: %s",
248 xbt_os_thread_free_thread_data(thread);
251 void xbt_os_thread_exit(int *retval)
253 pthread_exit(retval);
256 xbt_os_thread_t xbt_os_thread_self(void)
260 if (!thread_mod_inited)
263 res = pthread_getspecific(xbt_self_thread_key);
268 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
271 if ((errcode = pthread_key_create(key, NULL)))
272 THROWF(system_error, errcode, "pthread_key_create failed");
275 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
278 if ((errcode = pthread_setspecific(key, value)))
279 THROWF(system_error, errcode, "pthread_setspecific failed");
282 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
283 return pthread_getspecific(key);
286 void xbt_os_thread_detach(xbt_os_thread_t thread)
288 thread->detached = 1;
289 pthread_detach(thread->t);
293 void xbt_os_thread_yield(void)
298 void xbt_os_thread_cancel(xbt_os_thread_t t)
300 pthread_cancel(t->t);
303 /****** mutex related functions ******/
304 typedef struct xbt_os_mutex_ {
305 /* KEEP IT IN SYNC WITH xbt_thread.c */
312 xbt_os_mutex_t xbt_os_mutex_init(void)
314 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
317 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
318 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
324 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
328 if ((errcode = pthread_mutex_lock(&(mutex->m))))
329 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
330 mutex, strerror(errcode));
334 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
339 xbt_os_mutex_acquire(mutex);
341 } else if (delay == 0) {
342 errcode = pthread_mutex_trylock(&(mutex->m));
348 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
350 THROWF(system_error, errcode,
351 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
358 #ifdef HAVE_MUTEX_TIMEDLOCK
359 struct timespec ts_end;
360 double end = delay + xbt_os_time();
362 ts_end.tv_sec = (time_t) floor(end);
363 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
364 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
366 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
368 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
369 double start = xbt_os_time();
371 errcode = pthread_mutex_trylock(&(mutex->m));
372 if (errcode == EBUSY)
373 xbt_os_thread_yield();
374 } while (errcode == EBUSY && xbt_os_time() - start < delay);
376 if (errcode == EBUSY)
379 #endif /* HAVE_MUTEX_TIMEDLOCK */
386 THROWF(timeout_error, delay,
387 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
390 THROWF(system_error, errcode,
391 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
397 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
401 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
402 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
403 mutex, strerror(errcode));
406 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
413 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
414 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
415 mutex, strerror(errcode));
419 /***** condition related functions *****/
420 typedef struct xbt_os_cond_ {
421 /* KEEP IT IN SYNC WITH xbt_thread.c */
425 xbt_os_cond_t xbt_os_cond_init(void)
427 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
429 if ((errcode = pthread_cond_init(&(res->c), NULL)))
430 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
436 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
439 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
440 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
441 cond, mutex, strerror(errcode));
445 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
449 struct timespec ts_end;
450 double end = delay + xbt_os_time();
453 xbt_os_cond_wait(cond, mutex);
455 ts_end.tv_sec = (time_t) floor(end);
456 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
457 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
460 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
464 THROWF(timeout_error, errcode,
465 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
468 THROWF(system_error, errcode,
469 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
470 delay, strerror(errcode));
475 void xbt_os_cond_signal(xbt_os_cond_t cond)
478 if ((errcode = pthread_cond_signal(&(cond->c))))
479 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
480 cond, strerror(errcode));
483 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
486 if ((errcode = pthread_cond_broadcast(&(cond->c))))
487 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
488 cond, strerror(errcode));
491 void xbt_os_cond_destroy(xbt_os_cond_t cond)
498 if ((errcode = pthread_cond_destroy(&(cond->c))))
499 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
500 cond, strerror(errcode));
504 void *xbt_os_thread_getparam(void)
506 xbt_os_thread_t t = xbt_os_thread_self();
507 return t ? t->param : NULL;
510 typedef struct xbt_os_sem_ {
511 #ifndef HAVE_SEM_INIT
519 #define SEM_FAILED (-1)
522 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
524 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
526 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
527 * Any attempt to use it leads to ENOSYS (function not implemented).
528 * If such a prehistoric system is detected, do the job with sem_open instead
531 if (sem_init(&(res->s), 0, value) != 0)
532 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
535 #else /* damn, no sem_init(). Reimplement it */
537 xbt_os_mutex_acquire(next_sem_ID_lock);
538 res->name = bprintf("/%d", ++next_sem_ID);
539 xbt_os_mutex_release(next_sem_ID_lock);
541 res->ps = sem_open(res->name, O_CREAT, 0644, value);
542 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
543 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
544 res->name[13] = '\0';
545 res->ps = sem_open(res->name, O_CREAT, 0644, value);
547 if ((res->ps == (sem_t *) SEM_FAILED))
548 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
550 /* Remove the name from the semaphore namespace: we never join on it */
551 if (sem_unlink(res->name) < 0)
552 THROWF(system_error, errno, "sem_unlink() failed: %s",
560 void xbt_os_sem_acquire(xbt_os_sem_t sem)
563 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
564 if (sem_wait(sem->ps) < 0)
565 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
568 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
573 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
576 xbt_os_sem_acquire(sem);
577 } else if (delay == 0) {
578 errcode = sem_trywait(sem->ps);
584 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
586 THROWF(system_error, errcode,
587 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
593 struct timespec ts_end;
594 double end = delay + xbt_os_time();
596 ts_end.tv_sec = (time_t) floor(end);
597 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
598 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
599 errcode = sem_timedwait(sem->s, &ts_end);
601 #else /* Okay, reimplement this function then */
602 double start = xbt_os_time();
604 errcode = sem_trywait(sem->ps);
605 if (errcode == EBUSY)
606 xbt_os_thread_yield();
607 } while (errcode == EBUSY && xbt_os_time() - start < delay);
609 if (errcode == EBUSY)
618 THROWF(timeout_error, delay,
619 "semaphore %p wasn't signaled before timeout (%f)", sem,
623 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
624 delay, strerror(errcode));
629 void xbt_os_sem_release(xbt_os_sem_t sem)
632 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
634 if (sem_post(sem->ps) < 0)
635 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
638 void xbt_os_sem_destroy(xbt_os_sem_t sem)
641 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
644 if (sem_destroy(sem->ps) < 0)
645 THROWF(system_error, errno, "sem_destroy() failed: %s",
648 if (sem_close(sem->ps) < 0)
649 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
656 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
659 THROWF(arg_error, EINVAL,
660 "Cannot get the value of the NULL semaphore");
662 if (sem_getvalue(&(sem->s), svalue) < 0)
663 THROWF(system_error, errno, "sem_getvalue() failed: %s",
667 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
669 #elif defined(_XBT_WIN32)
673 typedef struct xbt_os_thread_ {
675 HANDLE handle; /* the win thread handle */
676 unsigned long id; /* the win thread id */
677 pvoid_f_pvoid_t start_routine;
682 /* so we can specify the size of the stack of the threads */
683 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
684 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
687 /* the default size of the stack of the threads (in bytes)*/
688 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
689 static int stack_size=0;
690 /* key to the TLS containing the xbt_os_thread_t structure */
691 static unsigned long xbt_self_thread_key;
693 void xbt_os_thread_mod_preinit(void)
695 xbt_self_thread_key = TlsAlloc();
698 void xbt_os_thread_mod_postexit(void)
701 if (!TlsFree(xbt_self_thread_key))
702 THROWF(system_error, (int) GetLastError(),
703 "TlsFree() failed to cleanup the thread submodule");
706 int xbt_os_thread_atfork(void (*prepare)(void),
707 void (*parent)(void), void (*child)(void))
712 static DWORD WINAPI wrapper_start_routine(void *s)
714 xbt_os_thread_t t = (xbt_os_thread_t) s;
717 if (!TlsSetValue(xbt_self_thread_key, t))
718 THROWF(system_error, (int) GetLastError(),
719 "TlsSetValue of data describing the created thread failed");
721 rv = (DWORD *) ((t->start_routine) (t->param));
728 xbt_os_thread_t xbt_os_thread_create(const char *name,
729 pvoid_f_pvoid_t start_routine,
734 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
736 t->name = xbt_strdup(name);
737 t->start_routine = start_routine;
739 t->extra_data = extra_data;
740 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
741 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
742 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
746 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
752 void xbt_os_thread_setstacksize(int size)
757 const char *xbt_os_thread_name(xbt_os_thread_t t)
762 const char *xbt_os_thread_self_name(void)
764 xbt_os_thread_t t = xbt_os_thread_self();
765 return t ? t->name : "main";
768 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
771 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
772 THROWF(system_error, (int) GetLastError(),
773 "WaitForSingleObject failed");
777 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
778 THROWF(system_error, (int) GetLastError(),
779 "GetExitCodeThread failed");
782 CloseHandle(thread->handle);
789 void xbt_os_thread_exit(int *retval)
797 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
802 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
804 if (!TlsSetValue(key, value))
805 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
808 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
809 return TlsGetValue(key);
812 void xbt_os_thread_detach(xbt_os_thread_t thread)
818 xbt_os_thread_t xbt_os_thread_self(void)
820 return TlsGetValue(xbt_self_thread_key);
823 void *xbt_os_thread_getparam(void)
825 xbt_os_thread_t t = xbt_os_thread_self();
830 void xbt_os_thread_yield(void)
835 void xbt_os_thread_cancel(xbt_os_thread_t t)
837 if (!TerminateThread(t->handle, 0))
838 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
841 /****** mutex related functions ******/
842 typedef struct xbt_os_mutex_ {
843 /* KEEP IT IN SYNC WITH xbt_thread.c */
844 CRITICAL_SECTION lock;
847 xbt_os_mutex_t xbt_os_mutex_init(void)
849 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
851 /* initialize the critical section object */
852 InitializeCriticalSection(&(res->lock));
857 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
859 EnterCriticalSection(&mutex->lock);
862 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
867 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
870 LeaveCriticalSection(&mutex->lock);
874 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
880 DeleteCriticalSection(&mutex->lock);
884 /***** condition related functions *****/
885 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
891 typedef struct xbt_os_cond_ {
892 /* KEEP IT IN SYNC WITH xbt_thread.c */
893 HANDLE events[MAX_EVENTS];
895 unsigned int waiters_count; /* the number of waiters */
896 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
899 xbt_os_cond_t xbt_os_cond_init(void)
902 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
904 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
906 /* initialize the critical section object */
907 InitializeCriticalSection(&res->waiters_count_lock);
909 res->waiters_count = 0;
911 /* Create an auto-reset event */
912 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
914 if (!res->events[SIGNAL]) {
915 DeleteCriticalSection(&res->waiters_count_lock);
917 THROWF(system_error, 0, "CreateEvent failed for the signals");
920 /* Create a manual-reset event. */
921 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
923 if (!res->events[BROADCAST]) {
925 DeleteCriticalSection(&res->waiters_count_lock);
926 CloseHandle(res->events[SIGNAL]);
928 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
934 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
937 unsigned long wait_result;
940 /* lock the threads counter and increment it */
941 EnterCriticalSection(&cond->waiters_count_lock);
942 cond->waiters_count++;
943 LeaveCriticalSection(&cond->waiters_count_lock);
945 /* unlock the mutex associate with the condition */
946 LeaveCriticalSection(&mutex->lock);
948 /* wait for a signal (broadcast or no) */
949 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
951 if (wait_result == WAIT_FAILED)
952 THROWF(system_error, 0,
953 "WaitForMultipleObjects failed, so we cannot wait on the condition");
955 /* we have a signal lock the condition */
956 EnterCriticalSection(&cond->waiters_count_lock);
957 cond->waiters_count--;
959 /* it's the last waiter or it's a broadcast ? */
960 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
961 && (cond->waiters_count == 0));
963 LeaveCriticalSection(&cond->waiters_count_lock);
965 /* yes it's the last waiter or it's a broadcast
966 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
970 if (!ResetEvent(cond->events[BROADCAST]))
971 THROWF(system_error, 0, "ResetEvent failed");
973 /* relock the mutex associated with the condition in accordance with the posix thread specification */
974 EnterCriticalSection(&mutex->lock);
977 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
981 unsigned long wait_result = WAIT_TIMEOUT;
983 unsigned long end = (unsigned long) (delay * 1000);
987 xbt_os_cond_wait(cond, mutex);
989 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
990 &(mutex->lock), end);
992 /* lock the threads counter and increment it */
993 EnterCriticalSection(&cond->waiters_count_lock);
994 cond->waiters_count++;
995 LeaveCriticalSection(&cond->waiters_count_lock);
997 /* unlock the mutex associate with the condition */
998 LeaveCriticalSection(&mutex->lock);
999 /* wait for a signal (broadcast or no) */
1001 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1003 switch (wait_result) {
1005 THROWF(timeout_error, GetLastError(),
1006 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1007 cond, mutex, delay);
1009 THROWF(system_error, GetLastError(),
1010 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1013 /* we have a signal lock the condition */
1014 EnterCriticalSection(&cond->waiters_count_lock);
1015 cond->waiters_count--;
1017 /* it's the last waiter or it's a broadcast ? */
1018 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1019 && (cond->waiters_count == 0));
1021 LeaveCriticalSection(&cond->waiters_count_lock);
1023 /* yes it's the last waiter or it's a broadcast
1024 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1028 if (!ResetEvent(cond->events[BROADCAST]))
1029 THROWF(system_error, 0, "ResetEvent failed");
1031 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1032 EnterCriticalSection(&mutex->lock);
1034 /*THROW_UNIMPLEMENTED; */
1037 void xbt_os_cond_signal(xbt_os_cond_t cond)
1041 EnterCriticalSection(&cond->waiters_count_lock);
1042 have_waiters = cond->waiters_count > 0;
1043 LeaveCriticalSection(&cond->waiters_count_lock);
1046 if (!SetEvent(cond->events[SIGNAL]))
1047 THROWF(system_error, 0, "SetEvent failed");
1049 xbt_os_thread_yield();
1052 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1056 EnterCriticalSection(&cond->waiters_count_lock);
1057 have_waiters = cond->waiters_count > 0;
1058 LeaveCriticalSection(&cond->waiters_count_lock);
1061 SetEvent(cond->events[BROADCAST]);
1064 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1071 if (!CloseHandle(cond->events[SIGNAL]))
1074 if (!CloseHandle(cond->events[BROADCAST]))
1077 DeleteCriticalSection(&cond->waiters_count_lock);
1082 THROWF(system_error, 0, "Error while destroying the condition");
1085 typedef struct xbt_os_sem_ {
1088 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1092 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1095 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1099 if (value > INT_MAX)
1100 THROWF(arg_error, value,
1101 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1104 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1106 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1107 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1108 strerror(GetLastError()));
1114 InitializeCriticalSection(&(res->value_lock));
1119 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1122 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1125 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1126 THROWF(system_error, GetLastError(),
1127 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1128 EnterCriticalSection(&(sem->value_lock));
1130 LeaveCriticalSection(&(sem->value_lock));
1133 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1137 double end = timeout + xbt_os_time();
1140 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1143 xbt_os_sem_acquire(sem);
1144 } else { /* timeout can be zero <-> try acquire ) */
1147 seconds = (long) floor(end);
1148 milliseconds = (long) ((end - seconds) * 1000);
1149 milliseconds += (seconds * 1000);
1151 switch (WaitForSingleObject(sem->h, milliseconds)) {
1153 EnterCriticalSection(&(sem->value_lock));
1155 LeaveCriticalSection(&(sem->value_lock));
1159 THROWF(timeout_error, GetLastError(),
1160 "semaphore %p wasn't signaled before timeout (%f)", sem,
1165 THROWF(system_error, GetLastError(),
1166 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1167 strerror(GetLastError()));
1172 void xbt_os_sem_release(xbt_os_sem_t sem)
1175 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1177 if (!ReleaseSemaphore(sem->h, 1, NULL))
1178 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1179 strerror(GetLastError()));
1180 EnterCriticalSection(&(sem->value_lock));
1182 LeaveCriticalSection(&(sem->value_lock));
1185 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1188 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1190 if (!CloseHandle(sem->h))
1191 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1192 strerror(GetLastError()));
1194 DeleteCriticalSection(&(sem->value_lock));
1200 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1203 THROWF(arg_error, EINVAL,
1204 "Cannot get the value of the NULL semaphore");
1206 EnterCriticalSection(&(sem->value_lock));
1207 *svalue = sem->value;
1208 LeaveCriticalSection(&(sem->value_lock));
1215 /** @brief Returns the amount of cores on the current host */
1216 int xbt_os_get_numcores(void) {
1218 SYSTEM_INFO sysinfo;
1219 GetSystemInfo(&sysinfo);
1220 return sysinfo.dwNumberOfProcessors;
1226 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1227 sysctl(nm, 2, &count, &len, NULL, 0);
1231 sysctl(nm, 2, &count, &len, NULL, 0);
1232 if(count < 1) { count = 1; }
1236 return sysconf(_SC_NPROCESSORS_ONLN);
1241 /***** reentrant mutexes *****/
1242 typedef struct xbt_os_rmutex_ {
1243 xbt_os_mutex_t mutex;
1244 xbt_os_thread_t owner;
1246 } s_xbt_os_rmutex_t;
1248 void xbt_os_thread_set_extra_data(void *data)
1250 xbt_os_thread_self()->extra_data = data;
1253 void *xbt_os_thread_get_extra_data(void)
1255 xbt_os_thread_t self = xbt_os_thread_self();
1256 return self? self->extra_data : NULL;
1259 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1261 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1262 rmutex->mutex = xbt_os_mutex_init();
1263 rmutex->owner = NULL;
1268 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1270 xbt_os_thread_t self = xbt_os_thread_self();
1273 /* the thread module is not initialized yet */
1274 rmutex->owner = NULL;
1278 if (self != rmutex->owner) {
1279 xbt_os_mutex_acquire(rmutex->mutex);
1280 rmutex->owner = self;
1287 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1289 if (rmutex->owner == NULL) {
1290 /* the thread module was not initialized */
1294 xbt_assert(rmutex->owner == xbt_os_thread_self());
1296 if (--rmutex->count == 0) {
1297 rmutex->owner = NULL;
1298 xbt_os_mutex_release(rmutex->mutex);
1302 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1304 xbt_os_mutex_destroy(rmutex->mutex);