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-2018. 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/internal_config.h"
41 #include "xbt/xbt_os_time.h" /* Portable time facilities */
42 #include "xbt/xbt_os_thread.h" /* This module */
43 #include "src/xbt_modinter.h" /* Initialization/finalization of this module */
45 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
47 /* use named semaphore when sem_init() does not work */
49 static int next_sem_ID = 0;
50 static xbt_os_mutex_t next_sem_ID_lock;
53 typedef struct xbt_os_thread_ {
57 pvoid_f_pvoid_t start_routine;
60 static xbt_os_thread_t main_thread = NULL;
62 /* thread-specific data containing the xbt_os_thread_t structure */
63 static pthread_key_t xbt_self_thread_key;
64 static int thread_mod_inited = 0;
66 /* defaults attribute for pthreads */
67 //FIXME: find where to put this
68 static pthread_attr_t thread_attr;
70 /* frees the xbt_os_thread_t corresponding to the current thread */
71 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
73 if (thread == main_thread) /* just killed main thread */
79 void xbt_os_thread_mod_preinit(void)
81 if (thread_mod_inited)
84 int errcode = pthread_key_create(&xbt_self_thread_key, NULL);
85 xbt_assert(errcode == 0, "pthread_key_create failed for xbt_self_thread_key");
87 main_thread = xbt_new(s_xbt_os_thread_t, 1);
88 main_thread->name = NULL;
89 main_thread->name = xbt_strdup("main");
90 main_thread->param = NULL;
91 main_thread->start_routine = NULL;
92 main_thread->extra_data = NULL;
94 if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
95 THROWF(system_error, errcode,
96 "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
98 pthread_attr_init(&thread_attr);
100 thread_mod_inited = 1;
103 next_sem_ID_lock = xbt_os_mutex_init();
107 void xbt_os_thread_mod_postexit(void)
109 /* FIXME: don't try to free our key on shutdown.
110 Valgrind detects no leak if we don't, and whine if we try to */
113 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
114 // THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
115 free(main_thread->name);
118 thread_mod_inited = 0;
120 xbt_os_mutex_destroy(next_sem_ID_lock);
124 /** Calls pthread_atfork() if present, and raise an exception otherwise.
126 * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
127 * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
128 * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
131 /* this function is critical to tesh+mmalloc, don't mess with it */
132 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
134 return pthread_atfork(prepare, parent, child);
137 static void *wrapper_start_routine(void *s)
139 xbt_os_thread_t t = s;
141 int errcode = pthread_setspecific(xbt_self_thread_key, t);
142 xbt_assert(errcode == 0, "pthread_setspecific failed for xbt_self_thread_key");
144 return t->start_routine(t->param);
147 xbt_os_thread_t xbt_os_thread_create(const char *name, pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
149 xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
150 res_thread->name = xbt_strdup(name);
151 res_thread->start_routine = start_routine;
152 res_thread->param = param;
153 res_thread->extra_data = extra_data;
155 int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
156 xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
161 /** Bind the thread to the given core, if possible.
163 * If pthread_setaffinity_np is not usable on that (non-gnu) platform, this function does nothing.
165 int xbt_os_thread_bind(XBT_ATTRIB_UNUSED xbt_os_thread_t thread, XBT_ATTRIB_UNUSED int cpu)
168 #if HAVE_PTHREAD_SETAFFINITY
169 pthread_t pthread = thread->t;
172 CPU_SET(cpu, &cpuset);
173 errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
178 void xbt_os_thread_setstacksize(int stack_size)
180 size_t alignment[] = {
182 #ifdef PTHREAD_STACK_MIN
188 xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
190 size_t sz = stack_size;
191 int res = pthread_attr_setstacksize(&thread_attr, sz);
193 for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
194 /* Invalid size, try again with next multiple of alignment[i]. */
195 size_t rem = sz % alignment[i];
196 if (rem != 0 || sz == 0) {
197 size_t sz2 = sz - rem + alignment[i];
198 XBT_DEBUG("pthread_attr_setstacksize failed for %zu, try again with %zu", sz, sz2);
200 res = pthread_attr_setstacksize(&thread_attr, sz);
205 XBT_WARN("invalid stack size (maybe too big): %zu", sz);
207 XBT_WARN("unknown error %d in pthread stacksize setting: %zu", res, sz);
210 void xbt_os_thread_setguardsize(int guard_size)
213 THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
215 size_t sz = guard_size;
216 int res = pthread_attr_setguardsize(&thread_attr, sz);
218 XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zu", res, sz);
222 const char *xbt_os_thread_self_name(void)
224 xbt_os_thread_t me = xbt_os_thread_self();
225 return me ? (const char *)me->name : "main";
228 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
230 int errcode = pthread_join(thread->t, thread_return);
232 xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
233 xbt_os_thread_free_thread_data(thread);
236 void xbt_os_thread_exit(int *retval)
238 pthread_exit(retval);
241 xbt_os_thread_t xbt_os_thread_self(void )
243 if (!thread_mod_inited)
246 return pthread_getspecific(xbt_self_thread_key);
249 /****** mutex related functions ******/
250 typedef struct xbt_os_mutex_ {
257 xbt_os_mutex_t xbt_os_mutex_init(void)
259 pthread_mutexattr_t Attr;
260 pthread_mutexattr_init(&Attr);
261 pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
263 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
264 int errcode = pthread_mutex_init(&(res->m), &Attr);
265 xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
270 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
272 int errcode = pthread_mutex_lock(&(mutex->m));
273 xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
276 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
278 int errcode = pthread_mutex_unlock(&(mutex->m));
279 xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
282 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
287 int errcode = pthread_mutex_destroy(&(mutex->m));
288 xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
292 typedef struct xbt_os_sem_ {
301 #define SEM_FAILED (-1)
304 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
306 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
308 /* On some systems (MAC OS X), only the stub of sem_init is to be found.
309 * Any attempt to use it leads to ENOSYS (function not implemented).
310 * If such a prehistoric system is detected, do the job with sem_open instead
313 if (sem_init(&(res->s), 0, value) != 0)
314 THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
317 #else /* damn, no sem_init(). Reimplement it */
319 xbt_os_mutex_acquire(next_sem_ID_lock);
320 res->name = bprintf("/sg-%d", ++next_sem_ID);
321 xbt_os_mutex_release(next_sem_ID_lock);
323 sem_unlink(res->name);
324 res->ps = sem_open(res->name, O_CREAT, 0644, value);
325 if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
326 /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
327 res->name[13] = '\0';
328 sem_unlink(res->name);
329 res->ps = sem_open(res->name, O_CREAT, 0644, value);
331 if (res->ps == (sem_t *) SEM_FAILED)
332 THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
334 /* Remove the name from the semaphore namespace: we never join on it */
335 if (sem_unlink(res->name) < 0)
336 THROWF(system_error, errno, "sem_unlink() failed: %s",
344 void xbt_os_sem_acquire(xbt_os_sem_t sem)
346 if (sem_wait(sem->ps) < 0)
347 THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
350 void xbt_os_sem_release(xbt_os_sem_t sem)
352 if (sem_post(sem->ps) < 0)
353 THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
356 void xbt_os_sem_destroy(xbt_os_sem_t sem)
359 if (sem_destroy(sem->ps) < 0)
360 THROWF(system_error, errno, "sem_destroy() failed: %s", strerror(errno));
362 if (sem_close(sem->ps) < 0)
363 THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
369 void xbt_os_thread_set_extra_data(void *data)
371 xbt_os_thread_self()->extra_data = data;
374 void *xbt_os_thread_get_extra_data(void)
376 xbt_os_thread_t thread = xbt_os_thread_self();
377 return thread ? thread->extra_data : NULL;