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-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 "internal_config.h"
21 #include "xbt/sysdep.h"
23 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
25 #include "xbt/xbt_os_time.h" /* Portable time facilities */
26 #include "xbt/xbt_os_thread.h" /* This module */
27 #include "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 = (char *) "main";
107 main_thread->start_routine = NULL;
108 main_thread->param = NULL;
109 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
110 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
112 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
113 THROWF(system_error, errcode,
114 "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
116 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
117 __xbt_ex_terminate = _os_thread_ex_terminate;
119 pthread_attr_init(&thread_attr);
121 thread_mod_inited = 1;
123 #ifndef HAVE_SEM_INIT
124 next_sem_ID_lock = xbt_os_mutex_init();
129 void xbt_os_thread_mod_postexit(void)
131 /* FIXME: don't try to free our key on shutdown.
132 Valgrind detects no leak if we don't, and whine if we try to */
135 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
136 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
137 free(main_thread->running_ctx);
140 thread_mod_inited = 0;
141 #ifndef HAVE_SEM_INIT
142 xbt_os_mutex_destroy(next_sem_ID_lock);
145 /* Restore the default exception setup */
146 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
147 __xbt_ex_terminate = &__xbt_ex_terminate_default;
150 /* this function is critical to tesh+mmalloc, don't mess with it */
151 int xbt_os_thread_atfork(void (*prepare)(void),
152 void (*parent)(void), void (*child)(void))
155 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
157 return pthread_atfork(prepare, parent, child);
161 static void *wrapper_start_routine(void *s)
163 xbt_os_thread_t t = s;
166 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
167 THROWF(system_error, errcode,
168 "pthread_setspecific failed for xbt_self_thread_key");
170 void *res = t->start_routine(t->param);
172 xbt_os_thread_free_thread_data(t);
177 xbt_os_thread_t xbt_os_thread_create(const char *name,
178 pvoid_f_pvoid_t start_routine,
184 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
185 res_thread->detached = 0;
186 res_thread->name = xbt_strdup(name);
187 res_thread->start_routine = start_routine;
188 res_thread->param = param;
189 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
190 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
191 res_thread->extra_data = extra_data;
193 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
194 wrapper_start_routine, res_thread)))
195 THROWF(system_error, errcode,
196 "pthread_create failed: %s", strerror(errcode));
205 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
206 pthread_t pthread = thread->t;
210 CPU_SET(cpu, &cpuset);
211 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
216 void xbt_os_thread_setstacksize(int stack_size)
218 size_t alignment[] = {
220 #ifdef PTHREAD_STACK_MIN
230 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
233 res = pthread_attr_setstacksize(&thread_attr, sz);
235 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
236 /* Invalid size, try again with next multiple of alignment[i]. */
237 size_t rem = sz % alignment[i];
238 if (rem != 0 || sz == 0) {
239 size_t sz2 = sz - rem + alignment[i];
240 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
243 res = pthread_attr_setstacksize(&thread_attr, sz);
248 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
250 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
253 void xbt_os_thread_setguardsize(int guard_size)
256 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
258 size_t sz = guard_size;
259 int res = pthread_attr_setguardsize(&thread_attr, sz);
261 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
265 const char *xbt_os_thread_name(xbt_os_thread_t t)
270 const char *xbt_os_thread_self_name(void)
272 xbt_os_thread_t me = xbt_os_thread_self();
273 return me ? me->name : "main";
276 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
281 if ((errcode = pthread_join(thread->t, thread_return)))
282 THROWF(system_error, errcode, "pthread_join failed: %s",
284 xbt_os_thread_free_thread_data(thread);
287 void xbt_os_thread_exit(int *retval)
289 pthread_exit(retval);
292 xbt_os_thread_t xbt_os_thread_self(void)
296 if (!thread_mod_inited)
299 res = pthread_getspecific(xbt_self_thread_key);
304 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
307 if ((errcode = pthread_key_create(key, NULL)))
308 THROWF(system_error, errcode, "pthread_key_create failed");
311 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
314 if ((errcode = pthread_setspecific(key, value)))
315 THROWF(system_error, errcode, "pthread_setspecific failed");
318 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
319 return pthread_getspecific(key);
322 void xbt_os_thread_detach(xbt_os_thread_t thread)
324 thread->detached = 1;
325 pthread_detach(thread->t);
329 void xbt_os_thread_yield(void)
334 void xbt_os_thread_cancel(xbt_os_thread_t t)
336 pthread_cancel(t->t);
339 /****** mutex related functions ******/
340 typedef struct xbt_os_mutex_ {
341 /* KEEP IT IN SYNC WITH xbt_thread.c */
348 xbt_os_mutex_t xbt_os_mutex_init(void)
350 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
353 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
354 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
360 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
364 if ((errcode = pthread_mutex_lock(&(mutex->m))))
365 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
366 mutex, strerror(errcode));
370 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
375 xbt_os_mutex_acquire(mutex);
377 } else if (delay == 0) {
378 errcode = pthread_mutex_trylock(&(mutex->m));
384 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
386 THROWF(system_error, errcode,
387 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
394 #ifdef HAVE_MUTEX_TIMEDLOCK
395 struct timespec ts_end;
396 double end = delay + xbt_os_time();
398 ts_end.tv_sec = (time_t) floor(end);
399 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
400 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
402 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
404 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
405 double start = xbt_os_time();
407 errcode = pthread_mutex_trylock(&(mutex->m));
408 if (errcode == EBUSY)
409 xbt_os_thread_yield();
410 } while (errcode == EBUSY && xbt_os_time() - start < delay);
412 if (errcode == EBUSY)
415 #endif /* HAVE_MUTEX_TIMEDLOCK */
422 THROWF(timeout_error, delay,
423 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
426 THROWF(system_error, errcode,
427 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
433 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
437 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
438 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
439 mutex, strerror(errcode));
442 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
449 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
450 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
451 mutex, strerror(errcode));
455 /***** condition related functions *****/
456 typedef struct xbt_os_cond_ {
457 /* KEEP IT IN SYNC WITH xbt_thread.c */
461 xbt_os_cond_t xbt_os_cond_init(void)
463 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
465 if ((errcode = pthread_cond_init(&(res->c), NULL)))
466 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
472 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
475 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
476 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
477 cond, mutex, strerror(errcode));
481 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
485 struct timespec ts_end;
486 double end = delay + xbt_os_time();
489 xbt_os_cond_wait(cond, mutex);
491 ts_end.tv_sec = (time_t) floor(end);
492 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
493 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
496 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
500 THROWF(timeout_error, errcode,
501 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
504 THROWF(system_error, errcode,
505 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
506 delay, strerror(errcode));
511 void xbt_os_cond_signal(xbt_os_cond_t cond)
514 if ((errcode = pthread_cond_signal(&(cond->c))))
515 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
516 cond, strerror(errcode));
519 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
522 if ((errcode = pthread_cond_broadcast(&(cond->c))))
523 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
524 cond, strerror(errcode));
527 void xbt_os_cond_destroy(xbt_os_cond_t cond)
534 if ((errcode = pthread_cond_destroy(&(cond->c))))
535 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
536 cond, strerror(errcode));
540 void *xbt_os_thread_getparam(void)
542 xbt_os_thread_t t = xbt_os_thread_self();
543 return t ? t->param : NULL;
546 typedef struct xbt_os_sem_ {
547 #ifndef HAVE_SEM_INIT
555 #define SEM_FAILED (-1)
558 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
560 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
562 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
563 * Any attempt to use it leads to ENOSYS (function not implemented).
564 * If such a prehistoric system is detected, do the job with sem_open instead
567 if (sem_init(&(res->s), 0, value) != 0)
568 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
571 #else /* damn, no sem_init(). Reimplement it */
573 xbt_os_mutex_acquire(next_sem_ID_lock);
574 res->name = bprintf("/%d", ++next_sem_ID);
575 xbt_os_mutex_release(next_sem_ID_lock);
577 res->ps = sem_open(res->name, O_CREAT, 0644, value);
578 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
579 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
580 res->name[13] = '\0';
581 res->ps = sem_open(res->name, O_CREAT, 0644, value);
583 if (res->ps == (sem_t *) SEM_FAILED)
584 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
586 /* Remove the name from the semaphore namespace: we never join on it */
587 if (sem_unlink(res->name) < 0)
588 THROWF(system_error, errno, "sem_unlink() failed: %s",
596 void xbt_os_sem_acquire(xbt_os_sem_t sem)
599 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
600 if (sem_wait(sem->ps) < 0)
601 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
604 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
609 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
612 xbt_os_sem_acquire(sem);
613 } else if (delay == 0) {
614 errcode = sem_trywait(sem->ps);
620 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
622 THROWF(system_error, errcode,
623 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
629 struct timespec ts_end;
630 double end = delay + xbt_os_time();
632 ts_end.tv_sec = (time_t) floor(end);
633 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
634 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
635 errcode = sem_timedwait(sem->s, &ts_end);
637 #else /* Okay, reimplement this function then */
638 double start = xbt_os_time();
640 errcode = sem_trywait(sem->ps);
641 if (errcode == EBUSY)
642 xbt_os_thread_yield();
643 } while (errcode == EBUSY && xbt_os_time() - start < delay);
645 if (errcode == EBUSY)
654 THROWF(timeout_error, delay,
655 "semaphore %p wasn't signaled before timeout (%f)", sem,
659 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
660 delay, strerror(errcode));
665 void xbt_os_sem_release(xbt_os_sem_t sem)
668 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
670 if (sem_post(sem->ps) < 0)
671 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
674 void xbt_os_sem_destroy(xbt_os_sem_t sem)
677 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
680 if (sem_destroy(sem->ps) < 0)
681 THROWF(system_error, errno, "sem_destroy() failed: %s",
684 if (sem_close(sem->ps) < 0)
685 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
692 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
695 THROWF(arg_error, EINVAL,
696 "Cannot get the value of the NULL semaphore");
698 if (sem_getvalue(&(sem->s), svalue) < 0)
699 THROWF(system_error, errno, "sem_getvalue() failed: %s",
703 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
705 #elif defined(_XBT_WIN32)
709 typedef struct xbt_os_thread_ {
711 HANDLE handle; /* the win thread handle */
712 unsigned long id; /* the win thread id */
713 pvoid_f_pvoid_t start_routine;
718 /* so we can specify the size of the stack of the threads */
719 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
720 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
723 /* the default size of the stack of the threads (in bytes)*/
724 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
725 static int stack_size=0;
726 /* key to the TLS containing the xbt_os_thread_t structure */
727 static unsigned long xbt_self_thread_key;
729 void xbt_os_thread_mod_preinit(void)
731 xbt_self_thread_key = TlsAlloc();
733 main_thread = xbt_new(s_xbt_os_thread_t, 1);
734 main_thread->name = (char *) "main";
735 main_thread->start_routine = NULL;
736 main_thread->param = NULL;
737 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
738 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
740 if (!TlsSetValue(xbt_self_thread_key, main_thread))
741 THROWF(system_error, errcode,
742 "Impossible to set the SimGrid identity descriptor to the main thread (TlsSetValue() failed)");
746 void xbt_os_thread_mod_postexit(void)
749 if (!TlsFree(xbt_self_thread_key))
750 THROWF(system_error, (int) GetLastError(),
751 "TlsFree() failed to cleanup the thread submodule");
754 int xbt_os_thread_atfork(void (*prepare)(void),
755 void (*parent)(void), void (*child)(void))
760 static DWORD WINAPI wrapper_start_routine(void *s)
762 xbt_os_thread_t t = (xbt_os_thread_t) s;
765 if (!TlsSetValue(xbt_self_thread_key, t))
766 THROWF(system_error, (int) GetLastError(),
767 "TlsSetValue of data describing the created thread failed");
769 rv = (DWORD *) ((t->start_routine) (t->param));
776 xbt_os_thread_t xbt_os_thread_create(const char *name,
777 pvoid_f_pvoid_t start_routine,
782 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
784 t->name = xbt_strdup(name);
785 t->start_routine = start_routine;
787 t->extra_data = extra_data;
788 t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
789 (LPTHREAD_START_ROUTINE) wrapper_start_routine,
790 t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
794 THROWF(system_error, (int) GetLastError(), "CreateThread failed");
800 void xbt_os_thread_setstacksize(int size)
805 void xbt_os_thread_setguardsize(int size)
807 XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
810 const char *xbt_os_thread_name(xbt_os_thread_t t)
815 const char *xbt_os_thread_self_name(void)
817 xbt_os_thread_t t = xbt_os_thread_self();
818 return t ? t->name : "main";
821 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
824 if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
825 THROWF(system_error, (int) GetLastError(),
826 "WaitForSingleObject failed");
830 if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
831 THROWF(system_error, (int) GetLastError(),
832 "GetExitCodeThread failed");
835 CloseHandle(thread->handle);
842 void xbt_os_thread_exit(int *retval)
850 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
855 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
857 if (!TlsSetValue(key, value))
858 THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
861 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
862 return TlsGetValue(key);
865 void xbt_os_thread_detach(xbt_os_thread_t thread)
871 xbt_os_thread_t xbt_os_thread_self(void)
873 return TlsGetValue(xbt_self_thread_key);
876 void *xbt_os_thread_getparam(void)
878 xbt_os_thread_t t = xbt_os_thread_self();
883 void xbt_os_thread_yield(void)
888 void xbt_os_thread_cancel(xbt_os_thread_t t)
890 if (!TerminateThread(t->handle, 0))
891 THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
894 /****** mutex related functions ******/
895 typedef struct xbt_os_mutex_ {
896 /* KEEP IT IN SYNC WITH xbt_thread.c */
897 CRITICAL_SECTION lock;
900 xbt_os_mutex_t xbt_os_mutex_init(void)
902 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
904 /* initialize the critical section object */
905 InitializeCriticalSection(&(res->lock));
910 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
912 EnterCriticalSection(&mutex->lock);
915 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
920 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
923 LeaveCriticalSection(&mutex->lock);
927 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
933 DeleteCriticalSection(&mutex->lock);
937 /***** condition related functions *****/
938 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
944 typedef struct xbt_os_cond_ {
945 /* KEEP IT IN SYNC WITH xbt_thread.c */
946 HANDLE events[MAX_EVENTS];
948 unsigned int waiters_count; /* the number of waiters */
949 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
952 xbt_os_cond_t xbt_os_cond_init(void)
955 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
957 memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
959 /* initialize the critical section object */
960 InitializeCriticalSection(&res->waiters_count_lock);
962 res->waiters_count = 0;
964 /* Create an auto-reset event */
965 res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
967 if (!res->events[SIGNAL]) {
968 DeleteCriticalSection(&res->waiters_count_lock);
970 THROWF(system_error, 0, "CreateEvent failed for the signals");
973 /* Create a manual-reset event. */
974 res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
976 if (!res->events[BROADCAST]) {
978 DeleteCriticalSection(&res->waiters_count_lock);
979 CloseHandle(res->events[SIGNAL]);
981 THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
987 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
990 unsigned long wait_result;
993 /* lock the threads counter and increment it */
994 EnterCriticalSection(&cond->waiters_count_lock);
995 cond->waiters_count++;
996 LeaveCriticalSection(&cond->waiters_count_lock);
998 /* unlock the mutex associate with the condition */
999 LeaveCriticalSection(&mutex->lock);
1001 /* wait for a signal (broadcast or no) */
1002 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
1004 if (wait_result == WAIT_FAILED)
1005 THROWF(system_error, 0,
1006 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1008 /* we have a signal lock the condition */
1009 EnterCriticalSection(&cond->waiters_count_lock);
1010 cond->waiters_count--;
1012 /* it's the last waiter or it's a broadcast ? */
1013 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1014 && (cond->waiters_count == 0));
1016 LeaveCriticalSection(&cond->waiters_count_lock);
1018 /* yes it's the last waiter or it's a broadcast
1019 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1023 if (!ResetEvent(cond->events[BROADCAST]))
1024 THROWF(system_error, 0, "ResetEvent failed");
1026 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1027 EnterCriticalSection(&mutex->lock);
1030 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1034 unsigned long wait_result = WAIT_TIMEOUT;
1036 unsigned long end = (unsigned long) (delay * 1000);
1040 xbt_os_cond_wait(cond, mutex);
1042 XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1043 &(mutex->lock), end);
1045 /* lock the threads counter and increment it */
1046 EnterCriticalSection(&cond->waiters_count_lock);
1047 cond->waiters_count++;
1048 LeaveCriticalSection(&cond->waiters_count_lock);
1050 /* unlock the mutex associate with the condition */
1051 LeaveCriticalSection(&mutex->lock);
1052 /* wait for a signal (broadcast or no) */
1054 wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1056 switch (wait_result) {
1058 THROWF(timeout_error, GetLastError(),
1059 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1060 cond, mutex, delay);
1062 THROWF(system_error, GetLastError(),
1063 "WaitForMultipleObjects failed, so we cannot wait on the condition");
1066 /* we have a signal lock the condition */
1067 EnterCriticalSection(&cond->waiters_count_lock);
1068 cond->waiters_count--;
1070 /* it's the last waiter or it's a broadcast ? */
1071 is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1072 && (cond->waiters_count == 0));
1074 LeaveCriticalSection(&cond->waiters_count_lock);
1076 /* yes it's the last waiter or it's a broadcast
1077 * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1081 if (!ResetEvent(cond->events[BROADCAST]))
1082 THROWF(system_error, 0, "ResetEvent failed");
1084 /* relock the mutex associated with the condition in accordance with the posix thread specification */
1085 EnterCriticalSection(&mutex->lock);
1087 /*THROW_UNIMPLEMENTED; */
1090 void xbt_os_cond_signal(xbt_os_cond_t cond)
1094 EnterCriticalSection(&cond->waiters_count_lock);
1095 have_waiters = cond->waiters_count > 0;
1096 LeaveCriticalSection(&cond->waiters_count_lock);
1099 if (!SetEvent(cond->events[SIGNAL]))
1100 THROWF(system_error, 0, "SetEvent failed");
1102 xbt_os_thread_yield();
1105 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1109 EnterCriticalSection(&cond->waiters_count_lock);
1110 have_waiters = cond->waiters_count > 0;
1111 LeaveCriticalSection(&cond->waiters_count_lock);
1114 SetEvent(cond->events[BROADCAST]);
1117 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1124 if (!CloseHandle(cond->events[SIGNAL]))
1127 if (!CloseHandle(cond->events[BROADCAST]))
1130 DeleteCriticalSection(&cond->waiters_count_lock);
1135 THROWF(system_error, 0, "Error while destroying the condition");
1138 typedef struct xbt_os_sem_ {
1141 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
1145 # define INT_MAX 32767 /* let's be safe by underestimating this value: this is for 16bits only */
1148 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1152 if (value > INT_MAX)
1153 THROWF(arg_error, value,
1154 "Semaphore initial value too big: %ud cannot be stored as a signed int",
1157 res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1159 if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1160 THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1161 strerror(GetLastError()));
1167 InitializeCriticalSection(&(res->value_lock));
1172 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1175 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1178 if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1179 THROWF(system_error, GetLastError(),
1180 "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1181 EnterCriticalSection(&(sem->value_lock));
1183 LeaveCriticalSection(&(sem->value_lock));
1186 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1190 double end = timeout + xbt_os_time();
1193 THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1196 xbt_os_sem_acquire(sem);
1197 } else { /* timeout can be zero <-> try acquire ) */
1200 seconds = (long) floor(end);
1201 milliseconds = (long) ((end - seconds) * 1000);
1202 milliseconds += (seconds * 1000);
1204 switch (WaitForSingleObject(sem->h, milliseconds)) {
1206 EnterCriticalSection(&(sem->value_lock));
1208 LeaveCriticalSection(&(sem->value_lock));
1212 THROWF(timeout_error, GetLastError(),
1213 "semaphore %p wasn't signaled before timeout (%f)", sem,
1218 THROWF(system_error, GetLastError(),
1219 "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1220 strerror(GetLastError()));
1225 void xbt_os_sem_release(xbt_os_sem_t sem)
1228 THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1230 if (!ReleaseSemaphore(sem->h, 1, NULL))
1231 THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1232 strerror(GetLastError()));
1233 EnterCriticalSection(&(sem->value_lock));
1235 LeaveCriticalSection(&(sem->value_lock));
1238 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1241 THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1243 if (!CloseHandle(sem->h))
1244 THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1245 strerror(GetLastError()));
1247 DeleteCriticalSection(&(sem->value_lock));
1253 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1256 THROWF(arg_error, EINVAL,
1257 "Cannot get the value of the NULL semaphore");
1259 EnterCriticalSection(&(sem->value_lock));
1260 *svalue = sem->value;
1261 LeaveCriticalSection(&(sem->value_lock));
1268 /** @brief Returns the amount of cores on the current host */
1269 int xbt_os_get_numcores(void) {
1271 SYSTEM_INFO sysinfo;
1272 GetSystemInfo(&sysinfo);
1273 return sysinfo.dwNumberOfProcessors;
1274 #elif defined(__APPLE__) && defined(__MACH__)
1279 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1280 sysctl(nm, 2, &count, &len, NULL, 0);
1284 sysctl(nm, 2, &count, &len, NULL, 0);
1285 if(count < 1) { count = 1; }
1289 return sysconf(_SC_NPROCESSORS_ONLN);
1294 /***** reentrant mutexes *****/
1295 typedef struct xbt_os_rmutex_ {
1296 xbt_os_mutex_t mutex;
1297 xbt_os_thread_t owner;
1299 } s_xbt_os_rmutex_t;
1301 void xbt_os_thread_set_extra_data(void *data)
1303 xbt_os_thread_self()->extra_data = data;
1306 void *xbt_os_thread_get_extra_data(void)
1308 xbt_os_thread_t self = xbt_os_thread_self();
1309 return self? self->extra_data : NULL;
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);