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. */
11 #include "src/internal_config.h"
12 #if HAVE_PTHREAD_SETAFFINITY
19 #if defined(__FreeBSD__)
20 #include "pthread_np.h"
21 #define cpu_set_t cpuset_t
25 #include <semaphore.h>
30 #elif defined(__MACH__) && defined(__APPLE__)
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
38 #include "xbt/sysdep.h"
40 #include "src/xbt/ex_interface.h" /* We play crude games with exceptions */
41 #include "src/internal_config.h"
42 #include "xbt/xbt_os_time.h" /* Portable time facilities */
43 #include "xbt/xbt_os_thread.h" /* This module */
44 #include "src/xbt_modinter.h" /* Initialization/finalization of this module */
46 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
48 /* use named sempahore when sem_init() does not work */
50 static int next_sem_ID = 0;
51 static xbt_os_mutex_t next_sem_ID_lock;
54 typedef struct xbt_os_thread_ {
59 pvoid_f_pvoid_t start_routine;
62 static xbt_os_thread_t main_thread = NULL;
64 /* thread-specific data containing the xbt_os_thread_t structure */
65 static pthread_key_t xbt_self_thread_key;
66 static int thread_mod_inited = 0;
68 /* defaults attribute for pthreads */
69 //FIXME: find where to put this
70 static pthread_attr_t thread_attr;
72 /* frees the xbt_os_thread_t corresponding to the current thread */
73 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
75 if (thread == main_thread) /* just killed main thread */
81 /* callback: termination */
82 static void _os_thread_ex_terminate(xbt_ex_t * e)
86 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
89 void xbt_os_thread_mod_preinit(void)
91 if (thread_mod_inited)
94 int errcode = pthread_key_create(&xbt_self_thread_key, NULL);
95 xbt_assert(errcode == 0, "pthread_key_create failed for xbt_self_thread_key");
97 main_thread = xbt_new(s_xbt_os_thread_t, 1);
98 main_thread->name = NULL;
99 main_thread->detached = 0;
100 main_thread->name = (char *) "main";
101 main_thread->param = NULL;
102 main_thread->start_routine = NULL;
103 main_thread->extra_data = NULL;
105 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
106 THROWF(system_error, errcode,
107 "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
109 pthread_attr_init(&thread_attr);
111 thread_mod_inited = 1;
114 next_sem_ID_lock = xbt_os_mutex_init();
118 void xbt_os_thread_mod_postexit(void)
120 /* FIXME: don't try to free our key on shutdown.
121 Valgrind detects no leak if we don't, and whine if we try to */
124 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
125 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
128 thread_mod_inited = 0;
130 xbt_os_mutex_destroy(next_sem_ID_lock);
134 /** Calls pthread_atfork() if present, and raise an exception otherwise.
136 * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
137 * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
138 * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
141 /* this function is critical to tesh+mmalloc, don't mess with it */
142 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
144 return pthread_atfork(prepare, parent, child);
147 static void *wrapper_start_routine(void *s)
149 xbt_os_thread_t t = s;
151 int errcode = pthread_setspecific(xbt_self_thread_key, t);
152 xbt_assert(errcode == 0, "pthread_setspecific failed for xbt_self_thread_key");
154 void *res = t->start_routine(t->param);
156 xbt_os_thread_free_thread_data(t);
160 xbt_os_thread_t xbt_os_thread_create(const char *name, pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
162 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
163 res_thread->detached = 0;
164 res_thread->name = xbt_strdup(name);
165 res_thread->start_routine = start_routine;
166 res_thread->param = param;
167 res_thread->extra_data = extra_data;
169 int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
170 xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
175 /** Bind the thread to the given core, if possible.
177 * If pthread_setaffinity_np is not usable on that (non-gnu) platform, this function does nothing.
179 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
181 #if HAVE_PTHREAD_SETAFFINITY
182 pthread_t pthread = thread->t;
185 CPU_SET(cpu, &cpuset);
186 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
191 void xbt_os_thread_setstacksize(int stack_size)
193 size_t alignment[] = {
195 #ifdef PTHREAD_STACK_MIN
201 xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
203 size_t sz = stack_size;
204 int res = pthread_attr_setstacksize(&thread_attr, sz);
206 for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
207 /* Invalid size, try again with next multiple of alignment[i]. */
208 size_t rem = sz % alignment[i];
209 if (rem != 0 || sz == 0) {
210 size_t sz2 = sz - rem + alignment[i];
211 XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd", sz, sz2);
213 res = pthread_attr_setstacksize(&thread_attr, sz);
218 XBT_WARN("invalid stack size (maybe too big): %zd", sz);
220 XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
223 void xbt_os_thread_setguardsize(int guard_size)
226 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
228 size_t sz = guard_size;
229 int res = pthread_attr_setguardsize(&thread_attr, sz);
231 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
235 const char *xbt_os_thread_self_name(void)
237 xbt_os_thread_t me = xbt_os_thread_self();
238 return me ? me->name : "main";
241 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
243 int errcode = pthread_join(thread->t, thread_return);
245 xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
246 xbt_os_thread_free_thread_data(thread);
249 void xbt_os_thread_exit(int *retval)
251 pthread_exit(retval);
254 xbt_os_thread_t xbt_os_thread_self(void)
256 if (!thread_mod_inited)
259 return pthread_getspecific(xbt_self_thread_key);
262 void xbt_os_thread_key_create(xbt_os_thread_key_t* key)
264 int errcode = pthread_key_create(key, NULL);
265 xbt_assert(errcode==0 , "pthread_key_create failed");
268 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value)
270 int errcode = pthread_setspecific(key, value);
271 xbt_assert(errcode==0, "pthread_setspecific failed");
274 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key)
276 return pthread_getspecific(key);
279 void xbt_os_thread_detach(xbt_os_thread_t thread)
281 thread->detached = 1;
282 pthread_detach(thread->t);
286 void xbt_os_thread_yield(void)
291 void xbt_os_thread_cancel(xbt_os_thread_t t)
293 pthread_cancel(t->t);
296 /****** mutex related functions ******/
297 typedef struct xbt_os_mutex_ {
304 xbt_os_mutex_t xbt_os_mutex_init(void)
306 pthread_mutexattr_t Attr;
307 pthread_mutexattr_init(&Attr);
308 pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
310 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
311 int errcode = pthread_mutex_init(&(res->m), &Attr);
312 xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
317 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
319 int errcode = pthread_mutex_lock(&(mutex->m));
320 xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
323 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
325 int errcode = pthread_mutex_unlock(&(mutex->m));
326 xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
329 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
334 int errcode = pthread_mutex_destroy(&(mutex->m));
335 xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
339 /***** condition related functions *****/
340 typedef struct xbt_os_cond_ {
344 xbt_os_cond_t xbt_os_cond_init(void)
346 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
347 int errcode = pthread_cond_init(&(res->c), NULL);
348 xbt_assert(errcode==0, "pthread_cond_init() failed: %s", strerror(errcode));
352 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
354 int errcode = pthread_cond_wait(&(cond->c), &(mutex->m));
355 xbt_assert(errcode==0, "pthread_cond_wait(%p,%p) failed: %s", cond, mutex, strerror(errcode));
358 void xbt_os_cond_signal(xbt_os_cond_t cond)
360 int errcode = pthread_cond_signal(&(cond->c));
361 xbt_assert(errcode==0, "pthread_cond_signal(%p) failed: %s", cond, strerror(errcode));
364 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
366 int errcode = pthread_cond_broadcast(&(cond->c));
367 xbt_assert(errcode==0, "pthread_cond_broadcast(%p) failed: %s", cond, strerror(errcode));
370 void xbt_os_cond_destroy(xbt_os_cond_t cond)
375 int errcode = pthread_cond_destroy(&(cond->c));
376 xbt_assert(errcode==0, "pthread_cond_destroy(%p) failed: %s", cond, strerror(errcode));
380 typedef struct xbt_os_sem_ {
389 #define SEM_FAILED (-1)
392 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
394 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
396 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
397 * Any attempt to use it leads to ENOSYS (function not implemented).
398 * If such a prehistoric system is detected, do the job with sem_open instead
401 if (sem_init(&(res->s), 0, value) != 0)
402 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
405 #else /* damn, no sem_init(). Reimplement it */
407 xbt_os_mutex_acquire(next_sem_ID_lock);
408 res->name = bprintf("/%d", ++next_sem_ID);
409 xbt_os_mutex_release(next_sem_ID_lock);
411 res->ps = sem_open(res->name, O_CREAT, 0644, value);
412 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
413 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
414 res->name[13] = '\0';
415 res->ps = sem_open(res->name, O_CREAT, 0644, value);
417 if (res->ps == (sem_t *) SEM_FAILED)
418 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
420 /* Remove the name from the semaphore namespace: we never join on it */
421 if (sem_unlink(res->name) < 0)
422 THROWF(system_error, errno, "sem_unlink() failed: %s",
430 void xbt_os_sem_acquire(xbt_os_sem_t sem)
432 if (sem_wait(sem->ps) < 0)
433 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
436 void xbt_os_sem_release(xbt_os_sem_t sem)
438 if (sem_post(sem->ps) < 0)
439 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
442 void xbt_os_sem_destroy(xbt_os_sem_t sem)
445 if (sem_destroy(sem->ps) < 0)
446 THROWF(system_error, errno, "sem_destroy() failed: %s", strerror(errno));
448 if (sem_close(sem->ps) < 0)
449 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
455 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
457 if (sem_getvalue(&(sem->s), svalue) < 0)
458 THROWF(system_error, errno, "sem_getvalue() failed: %s",
462 /** @brief Returns the amount of cores on the current host */
463 int xbt_os_get_numcores(void) {
466 GetSystemInfo(&sysinfo);
467 return sysinfo.dwNumberOfProcessors;
468 #elif defined(__APPLE__) && defined(__MACH__)
473 nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
474 sysctl(nm, 2, &count, &len, NULL, 0);
478 sysctl(nm, 2, &count, &len, NULL, 0);
479 if(count < 1) { count = 1; }
483 return sysconf(_SC_NPROCESSORS_ONLN);
487 void xbt_os_thread_set_extra_data(void *data)
489 xbt_os_thread_self()->extra_data = data;
492 void *xbt_os_thread_get_extra_data(void)
494 xbt_os_thread_t thread = xbt_os_thread_self();
495 return thread ? thread->extra_data : NULL;