1 /* xbt_os_thread -- portability layer over the pthread API */
2 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD */
3 /* in SG, when using HAVE_UCONTEXT_CONTEXTS, xbt_os_thread_stub is used instead */
5 /* Copyright (c) 2007-2015. The SimGrid Team.
6 * All rights reserved. */
8 /* This program is free software; you can redistribute it and/or modify it
9 * under the terms of the license (GNU LGPL) which comes with this package. */
12 #elif defined(__MACH__) && defined(__APPLE__)
14 #include <sys/types.h>
15 #include <sys/sysctl.h>
20 #include "src/internal_config.h"
21 #include "xbt/sysdep.h"
23 #include "src/xbt/ex_interface.h" /* We play crude games with exceptions */
24 #include "src/portable.h"
25 #include "xbt/xbt_os_time.h" /* Portable time facilities */
26 #include "xbt/xbt_os_thread.h" /* This module */
27 #include "src/xbt_modinter.h" /* Initialization/finalization of this module */
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
30 "Synchronization mechanism (OS-level)");
32 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
35 #include <semaphore.h>
42 /* use named sempahore when sem_init() does not work */
44 static int next_sem_ID = 0;
45 static xbt_os_mutex_t next_sem_ID_lock;
48 typedef struct xbt_os_thread_ {
53 pvoid_f_pvoid_t start_routine;
54 xbt_running_ctx_t *running_ctx;
57 static xbt_os_thread_t main_thread = NULL;
59 /* thread-specific data containing the xbt_os_thread_t structure */
60 static pthread_key_t xbt_self_thread_key;
61 static int thread_mod_inited = 0;
63 /* defaults attribute for pthreads */
64 //FIXME: find where to put this
65 static pthread_attr_t thread_attr;
67 /* frees the xbt_os_thread_t corresponding to the current thread */
68 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
70 if (thread == main_thread) /* just killed main thread */
73 free(thread->running_ctx);
78 /* callback: context fetching */
79 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
81 return xbt_os_thread_self()->running_ctx;
84 /* callback: termination */
85 static void _os_thread_ex_terminate(xbt_ex_t * e)
89 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
92 void xbt_os_thread_mod_preinit(void)
96 if (thread_mod_inited)
99 if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
100 THROWF(system_error, errcode,
101 "pthread_key_create failed for xbt_self_thread_key");
103 main_thread = xbt_new(s_xbt_os_thread_t, 1);
104 main_thread->name = NULL;
105 main_thread->detached = 0;
106 main_thread->name = (char *) "main";
107 main_thread->param = NULL;
108 main_thread->start_routine = NULL;
109 main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
110 main_thread->extra_data = NULL;
111 XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
113 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
114 THROWF(system_error, errcode,
115 "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
117 __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
118 __xbt_ex_terminate = _os_thread_ex_terminate;
120 pthread_attr_init(&thread_attr);
122 thread_mod_inited = 1;
124 #ifndef HAVE_SEM_INIT
125 next_sem_ID_lock = xbt_os_mutex_init();
130 void xbt_os_thread_mod_postexit(void)
132 /* FIXME: don't try to free our key on shutdown.
133 Valgrind detects no leak if we don't, and whine if we try to */
136 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
137 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
138 free(main_thread->running_ctx);
141 thread_mod_inited = 0;
142 #ifndef HAVE_SEM_INIT
143 xbt_os_mutex_destroy(next_sem_ID_lock);
146 /* Restore the default exception setup */
147 __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
148 __xbt_ex_terminate = &__xbt_ex_terminate_default;
151 /* this function is critical to tesh+mmalloc, don't mess with it */
152 int xbt_os_thread_atfork(void (*prepare)(void),
153 void (*parent)(void), void (*child)(void))
156 THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
158 return pthread_atfork(prepare, parent, child);
162 static void *wrapper_start_routine(void *s)
164 xbt_os_thread_t t = s;
167 if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
168 THROWF(system_error, errcode,
169 "pthread_setspecific failed for xbt_self_thread_key");
171 void *res = t->start_routine(t->param);
173 xbt_os_thread_free_thread_data(t);
178 xbt_os_thread_t xbt_os_thread_create(const char *name,
179 pvoid_f_pvoid_t start_routine,
185 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
186 res_thread->detached = 0;
187 res_thread->name = xbt_strdup(name);
188 res_thread->start_routine = start_routine;
189 res_thread->param = param;
190 res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
191 XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
192 res_thread->extra_data = extra_data;
194 if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
195 wrapper_start_routine, res_thread)))
196 THROWF(system_error, errcode,
197 "pthread_create failed: %s", strerror(errcode));
206 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
207 pthread_t pthread = thread->t;
211 CPU_SET(cpu, &cpuset);
212 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
217 void xbt_os_thread_setstacksize(int stack_size)
219 size_t alignment[] = {
221 #ifdef PTHREAD_STACK_MIN
231 xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
234 res = pthread_attr_setstacksize(&thread_attr, sz);
236 for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
237 /* Invalid size, try again with next multiple of alignment[i]. */
238 size_t rem = sz % alignment[i];
239 if (rem != 0 || sz == 0) {
240 size_t sz2 = sz - rem + alignment[i];
241 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
244 res = pthread_attr_setstacksize(&thread_attr, sz);
249 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
251 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
254 void xbt_os_thread_setguardsize(int guard_size)
257 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
259 size_t sz = guard_size;
260 int res = pthread_attr_setguardsize(&thread_attr, sz);
262 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
266 const char *xbt_os_thread_name(xbt_os_thread_t t)
271 const char *xbt_os_thread_self_name(void)
273 xbt_os_thread_t me = xbt_os_thread_self();
274 return me ? me->name : "main";
277 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
282 if ((errcode = pthread_join(thread->t, thread_return)))
283 THROWF(system_error, errcode, "pthread_join failed: %s",
285 xbt_os_thread_free_thread_data(thread);
288 void xbt_os_thread_exit(int *retval)
290 pthread_exit(retval);
293 xbt_os_thread_t xbt_os_thread_self(void)
295 if (!thread_mod_inited)
298 return pthread_getspecific(xbt_self_thread_key);
301 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
304 if ((errcode = pthread_key_create(key, NULL)))
305 THROWF(system_error, errcode, "pthread_key_create failed");
308 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
311 if ((errcode = pthread_setspecific(key, value)))
312 THROWF(system_error, errcode, "pthread_setspecific failed");
315 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
316 return pthread_getspecific(key);
319 void xbt_os_thread_detach(xbt_os_thread_t thread)
321 thread->detached = 1;
322 pthread_detach(thread->t);
326 void xbt_os_thread_yield(void)
331 void xbt_os_thread_cancel(xbt_os_thread_t t)
333 pthread_cancel(t->t);
336 /****** mutex related functions ******/
337 typedef struct xbt_os_mutex_ {
338 /* KEEP IT IN SYNC WITH xbt_thread.c */
345 xbt_os_mutex_t xbt_os_mutex_init(void)
347 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
350 if ((errcode = pthread_mutex_init(&(res->m), NULL)))
351 THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
357 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
361 if ((errcode = pthread_mutex_lock(&(mutex->m))))
362 THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
363 mutex, strerror(errcode));
367 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
372 xbt_os_mutex_acquire(mutex);
374 } else if (delay == 0) {
375 errcode = pthread_mutex_trylock(&(mutex->m));
381 THROWF(timeout_error, 0, "mutex %p not ready", mutex);
383 THROWF(system_error, errcode,
384 "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
391 #ifdef HAVE_MUTEX_TIMEDLOCK
392 struct timespec ts_end;
393 double end = delay + xbt_os_time();
395 ts_end.tv_sec = (time_t) floor(end);
396 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
397 XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
399 errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
401 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
402 double start = xbt_os_time();
404 errcode = pthread_mutex_trylock(&(mutex->m));
405 if (errcode == EBUSY)
406 xbt_os_thread_yield();
407 } while (errcode == EBUSY && xbt_os_time() - start < delay);
409 if (errcode == EBUSY)
412 #endif /* HAVE_MUTEX_TIMEDLOCK */
419 THROWF(timeout_error, delay,
420 "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
423 THROWF(system_error, errcode,
424 "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
430 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
434 if ((errcode = pthread_mutex_unlock(&(mutex->m))))
435 THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
436 mutex, strerror(errcode));
439 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
446 if ((errcode = pthread_mutex_destroy(&(mutex->m))))
447 THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
448 mutex, strerror(errcode));
452 /***** condition related functions *****/
453 typedef struct xbt_os_cond_ {
454 /* KEEP IT IN SYNC WITH xbt_thread.c */
458 xbt_os_cond_t xbt_os_cond_init(void)
460 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
462 if ((errcode = pthread_cond_init(&(res->c), NULL)))
463 THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
469 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
472 if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
473 THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
474 cond, mutex, strerror(errcode));
478 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
482 struct timespec ts_end;
483 double end = delay + xbt_os_time();
486 xbt_os_cond_wait(cond, mutex);
488 ts_end.tv_sec = (time_t) floor(end);
489 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
490 XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
493 pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
497 THROWF(timeout_error, errcode,
498 "condition %p (mutex %p) wasn't signaled before timeout (%f)",
501 THROWF(system_error, errcode,
502 "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
503 delay, strerror(errcode));
508 void xbt_os_cond_signal(xbt_os_cond_t cond)
511 if ((errcode = pthread_cond_signal(&(cond->c))))
512 THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
513 cond, strerror(errcode));
516 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
519 if ((errcode = pthread_cond_broadcast(&(cond->c))))
520 THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
521 cond, strerror(errcode));
524 void xbt_os_cond_destroy(xbt_os_cond_t cond)
531 if ((errcode = pthread_cond_destroy(&(cond->c))))
532 THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
533 cond, strerror(errcode));
537 void *xbt_os_thread_getparam(void)
539 xbt_os_thread_t t = xbt_os_thread_self();
540 return t ? t->param : NULL;
543 typedef struct xbt_os_sem_ {
544 #ifndef HAVE_SEM_INIT
552 #define SEM_FAILED (-1)
555 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
557 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
559 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
560 * Any attempt to use it leads to ENOSYS (function not implemented).
561 * If such a prehistoric system is detected, do the job with sem_open instead
564 if (sem_init(&(res->s), 0, value) != 0)
565 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
568 #else /* damn, no sem_init(). Reimplement it */
570 xbt_os_mutex_acquire(next_sem_ID_lock);
571 res->name = bprintf("/%d", ++next_sem_ID);
572 xbt_os_mutex_release(next_sem_ID_lock);
574 res->ps = sem_open(res->name, O_CREAT, 0644, value);
575 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
576 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
577 res->name[13] = '\0';
578 res->ps = sem_open(res->name, O_CREAT, 0644, value);
580 if (res->ps == (sem_t *) SEM_FAILED)
581 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
583 /* Remove the name from the semaphore namespace: we never join on it */
584 if (sem_unlink(res->name) < 0)
585 THROWF(system_error, errno, "sem_unlink() failed: %s",
593 void xbt_os_sem_acquire(xbt_os_sem_t sem)
596 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
597 if (sem_wait(sem->ps) < 0)
598 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
601 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
606 THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
609 xbt_os_sem_acquire(sem);
610 } else if (delay == 0) {
611 errcode = sem_trywait(sem->ps);
617 THROWF(timeout_error, 0, "semaphore %p not ready", sem);
619 THROWF(system_error, errcode,
620 "xbt_os_sem_timedacquire(%p) failed: %s", sem,
626 struct timespec ts_end;
627 double end = delay + xbt_os_time();
629 ts_end.tv_sec = (time_t) floor(end);
630 ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
631 XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
632 errcode = sem_timedwait(sem->s, &ts_end);
634 #else /* Okay, reimplement this function then */
635 double start = xbt_os_time();
637 errcode = sem_trywait(sem->ps);
638 if (errcode == EBUSY)
639 xbt_os_thread_yield();
640 } while (errcode == EBUSY && xbt_os_time() - start < delay);
642 if (errcode == EBUSY)
651 THROWF(timeout_error, delay,
652 "semaphore %p wasn't signaled before timeout (%f)", sem,
656 THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
657 delay, strerror(errcode));
662 void xbt_os_sem_release(xbt_os_sem_t sem)
665 THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
667 if (sem_post(sem->ps) < 0)
668 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
671 void xbt_os_sem_destroy(xbt_os_sem_t sem)
674 THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
677 if (sem_destroy(sem->ps) < 0)
678 THROWF(system_error, errno, "sem_destroy() failed: %s",
681 if (sem_close(sem->ps) < 0)
682 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
689 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
692 THROWF(arg_error, EINVAL,
693 "Cannot get the value of the NULL semaphore");
695 if (sem_getvalue(&(sem->s), svalue) < 0)
696 THROWF(system_error, errno, "sem_getvalue() failed: %s",
701 /** @brief Returns the amount of cores on the current host */
702 int xbt_os_get_numcores(void) {
705 GetSystemInfo(&sysinfo);
706 return sysinfo.dwNumberOfProcessors;
707 #elif defined(__APPLE__) && defined(__MACH__)
712 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
713 sysctl(nm, 2, &count, &len, NULL, 0);
717 sysctl(nm, 2, &count, &len, NULL, 0);
718 if(count < 1) { count = 1; }
722 return sysconf(_SC_NPROCESSORS_ONLN);
727 /***** reentrant mutexes *****/
728 typedef struct xbt_os_rmutex_ {
729 xbt_os_mutex_t mutex;
730 xbt_os_thread_t owner;
734 void xbt_os_thread_set_extra_data(void *data)
736 xbt_os_thread_self()->extra_data = data;
739 void *xbt_os_thread_get_extra_data(void)
741 xbt_os_thread_t thread = xbt_os_thread_self();
743 return xbt_os_thread_self()->extra_data;
748 xbt_os_rmutex_t xbt_os_rmutex_init(void)
750 xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
751 rmutex->mutex = xbt_os_mutex_init();
752 rmutex->owner = NULL;
757 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
759 xbt_os_thread_t self = xbt_os_thread_self();
762 /* the thread module is not initialized yet */
763 rmutex->owner = NULL;
767 if (self != rmutex->owner) {
768 xbt_os_mutex_acquire(rmutex->mutex);
769 rmutex->owner = self;
776 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
778 if (rmutex->owner == NULL) {
779 /* the thread module was not initialized */
783 xbt_assert(rmutex->owner == xbt_os_thread_self());
785 if (--rmutex->count == 0) {
786 rmutex->owner = NULL;
787 xbt_os_mutex_release(rmutex->mutex);
791 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
793 xbt_os_mutex_destroy(rmutex->mutex);