Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
4361e4148ea677272d630ccd80ca614decdd0486
[simgrid.git] / src / xbt / xbt_os_thread.c
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   */
4
5 /* Copyright (c) 2007-2018. The SimGrid Team. All rights reserved.          */
6
7 /* This program is free software; you can redistribute it and/or modify it
8  * under the terms of the license (GNU LGPL) which comes with this package. */
9
10 #include "src/internal_config.h"
11 #if HAVE_PTHREAD_SETAFFINITY
12 #define _GNU_SOURCE
13 #include <sched.h>
14 #endif
15
16 #include <pthread.h>
17
18 #if defined(__FreeBSD__)
19 #include "pthread_np.h"
20 #define cpu_set_t cpuset_t
21 #endif
22
23 #include <limits.h>
24 #include <semaphore.h>
25 #include <errno.h>
26
27 #if defined(_WIN32)
28 #include <windows.h>
29 #elif defined(__MACH__) && defined(__APPLE__)
30 #include <stdint.h>
31 #include <sys/types.h>
32 #include <sys/sysctl.h>
33 #else
34 #include <unistd.h>
35 #endif
36
37 #include "xbt/sysdep.h"
38 #include "xbt/ex.h"
39 #include "src/internal_config.h"
40 #include "xbt/xbt_os_time.h"       /* Portable time facilities */
41 #include "xbt/xbt_os_thread.h"     /* This module */
42 #include "src/xbt_modinter.h"      /* Initialization/finalization of this module */
43
44 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
45
46 typedef struct xbt_os_thread_ {
47   pthread_t t;
48   char *name;
49   void *param;
50   pvoid_f_pvoid_t start_routine;
51   void *extra_data;
52 } s_xbt_os_thread_t;
53 static xbt_os_thread_t main_thread = NULL;
54
55 /* thread-specific data containing the xbt_os_thread_t structure */
56 static pthread_key_t xbt_self_thread_key;
57 static int thread_mod_inited = 0;
58
59 /* defaults attribute for pthreads */
60 //FIXME: find where to put this
61 static pthread_attr_t thread_attr;
62
63 /* frees the xbt_os_thread_t corresponding to the current thread */
64 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
65 {
66   if (thread == main_thread)    /* just killed main thread */
67     main_thread = NULL;
68   free(thread->name);
69   free(thread);
70 }
71
72 void xbt_os_thread_mod_preinit(void)
73 {
74   if (thread_mod_inited)
75     return;
76
77   int errcode = pthread_key_create(&xbt_self_thread_key, NULL);
78   xbt_assert(errcode == 0, "pthread_key_create failed for xbt_self_thread_key");
79
80   main_thread = xbt_new(s_xbt_os_thread_t, 1);
81   main_thread->name = NULL;
82   main_thread->name = xbt_strdup("main");
83   main_thread->param = NULL;
84   main_thread->start_routine = NULL;
85   main_thread->extra_data = NULL;
86
87   if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
88     THROWF(system_error, errcode,
89            "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
90
91   pthread_attr_init(&thread_attr);
92
93   thread_mod_inited = 1;
94 }
95
96 void xbt_os_thread_mod_postexit(void)
97 {
98   /* FIXME: don't try to free our key on shutdown.
99      Valgrind detects no leak if we don't, and whine if we try to */
100   //   int errcode;
101
102   //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
103   //     THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
104   free(main_thread->name);
105   free(main_thread);
106   main_thread = NULL;
107   thread_mod_inited = 0;
108 }
109
110 /** Calls pthread_atfork() if present, and raise an exception otherwise.
111  *
112  * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
113  * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
114  * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
115  */
116
117 /* this function is critical to tesh+mmalloc, don't mess with it */
118 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
119 {
120   return pthread_atfork(prepare, parent, child);
121 }
122
123 static void *wrapper_start_routine(void *s)
124 {
125   xbt_os_thread_t t = s;
126
127   int errcode = pthread_setspecific(xbt_self_thread_key, t);
128   xbt_assert(errcode == 0, "pthread_setspecific failed for xbt_self_thread_key");
129
130   return t->start_routine(t->param);
131 }
132
133 xbt_os_thread_t xbt_os_thread_create(const char *name,  pvoid_f_pvoid_t start_routine, void *param, void *extra_data)
134 {
135   xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
136   res_thread->name = xbt_strdup(name);
137   res_thread->start_routine = start_routine;
138   res_thread->param = param;
139   res_thread->extra_data = extra_data;
140
141   int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
142   xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
143
144   return res_thread;
145 }
146
147 /** Bind the thread to the given core, if possible.
148  *
149  * If pthread_setaffinity_np is not usable on that (non-gnu) platform, this function does nothing.
150  */
151 int xbt_os_thread_bind(XBT_ATTRIB_UNUSED xbt_os_thread_t thread, XBT_ATTRIB_UNUSED int cpu)
152 {
153   int errcode = 0;
154 #if HAVE_PTHREAD_SETAFFINITY
155   pthread_t pthread = thread->t;
156   cpu_set_t cpuset;
157   CPU_ZERO(&cpuset);
158   CPU_SET(cpu, &cpuset);
159   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
160 #endif
161   return errcode;
162 }
163
164 void xbt_os_thread_setstacksize(int stack_size)
165 {
166   size_t alignment[] = {
167     xbt_pagesize,
168 #ifdef PTHREAD_STACK_MIN
169     PTHREAD_STACK_MIN,
170 #endif
171     0
172   };
173
174   xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
175
176   size_t sz = stack_size;
177   int res = pthread_attr_setstacksize(&thread_attr, sz);
178
179   for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
180     /* Invalid size, try again with next multiple of alignment[i]. */
181     size_t rem = sz % alignment[i];
182     if (rem != 0 || sz == 0) {
183       size_t sz2 = sz - rem + alignment[i];
184       XBT_DEBUG("pthread_attr_setstacksize failed for %zu, try again with %zu", sz, sz2);
185       sz = sz2;
186       res = pthread_attr_setstacksize(&thread_attr, sz);
187     }
188   }
189
190   if (res == EINVAL)
191     XBT_WARN("invalid stack size (maybe too big): %zu", sz);
192   else if (res != 0)
193     XBT_WARN("unknown error %d in pthread stacksize setting: %zu", res, sz);
194 }
195
196 void xbt_os_thread_setguardsize(int guard_size)
197 {
198 #ifdef WIN32
199   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
200 #else
201   size_t sz = guard_size;
202   int res = pthread_attr_setguardsize(&thread_attr, sz);
203   if (res)
204     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zu", res, sz);
205 #endif
206 }
207
208 const char *xbt_os_thread_self_name(void)
209 {
210   xbt_os_thread_t me = xbt_os_thread_self();
211   return me ? (const char *)me->name : "main";
212 }
213
214 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
215 {
216   int errcode = pthread_join(thread->t, thread_return);
217
218   xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
219   xbt_os_thread_free_thread_data(thread);
220 }
221
222 void xbt_os_thread_exit(int *retval)
223 {
224   pthread_exit(retval);
225 }
226
227 xbt_os_thread_t xbt_os_thread_self(void )
228 {
229   if (!thread_mod_inited)
230     return NULL;
231
232   return pthread_getspecific(xbt_self_thread_key);
233 }
234
235 /****** mutex related functions ******/
236 typedef struct xbt_os_mutex_ {
237   pthread_mutex_t m;
238 } s_xbt_os_mutex_t;
239
240 #include <time.h>
241 #include <math.h>
242
243 xbt_os_mutex_t xbt_os_mutex_init(void)
244 {
245   pthread_mutexattr_t Attr;
246   pthread_mutexattr_init(&Attr);
247   pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
248
249   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
250   int errcode = pthread_mutex_init(&(res->m), &Attr);
251   xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
252
253   return res;
254 }
255
256 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
257 {
258   int errcode = pthread_mutex_lock(&(mutex->m));
259   xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
260 }
261
262 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
263 {
264   int errcode = pthread_mutex_unlock(&(mutex->m));
265   xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
266 }
267
268 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
269 {
270   if (!mutex)
271     return;
272
273   int errcode = pthread_mutex_destroy(&(mutex->m));
274   xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
275   free(mutex);
276 }
277
278 void xbt_os_thread_set_extra_data(void *data)
279 {
280   xbt_os_thread_self()->extra_data = data;
281 }
282
283 void *xbt_os_thread_get_extra_data(void)
284 {
285   xbt_os_thread_t thread = xbt_os_thread_self();
286   return thread ? thread->extra_data : NULL;
287 }