Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Document last change
[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-2019. 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   void *param;
49   pvoid_f_pvoid_t start_routine;
50 } s_xbt_os_thread_t;
51 static xbt_os_thread_t main_thread = NULL;
52
53 /* thread-specific data containing the xbt_os_thread_t structure */
54 static int thread_mod_inited = 0;
55
56 /* defaults attribute for pthreads */
57 static pthread_attr_t thread_attr;
58
59 /* frees the xbt_os_thread_t corresponding to the current thread */
60 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
61 {
62   if (thread == main_thread)    /* just killed main thread */
63     main_thread = NULL;
64   free(thread);
65 }
66
67 void xbt_os_thread_mod_preinit(void)
68 {
69   if (thread_mod_inited)
70     return;
71
72   main_thread = xbt_new(s_xbt_os_thread_t, 1);
73   main_thread->param = NULL;
74   main_thread->start_routine = NULL;
75
76   pthread_attr_init(&thread_attr);
77
78   thread_mod_inited = 1;
79 }
80
81 void xbt_os_thread_mod_postexit(void)
82 {
83   free(main_thread);
84   main_thread = NULL;
85   thread_mod_inited = 0;
86 }
87
88 /** Calls pthread_atfork() if present, and raise an exception otherwise.
89  *
90  * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
91  * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
92  * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
93  */
94
95 /* this function is critical to tesh+mmalloc, don't mess with it */
96 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
97 {
98   return pthread_atfork(prepare, parent, child);
99 }
100
101 static void *wrapper_start_routine(void *s)
102 {
103   xbt_os_thread_t t = s;
104
105   return t->start_routine(t->param);
106 }
107
108 xbt_os_thread_t xbt_os_thread_create(pvoid_f_pvoid_t start_routine, void* param)
109 {
110   xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
111   res_thread->start_routine = start_routine;
112   res_thread->param = param;
113
114   int errcode = pthread_create(&(res_thread->t), &thread_attr, wrapper_start_routine, res_thread);
115   xbt_assert(errcode == 0, "pthread_create failed: %s", strerror(errcode));
116
117   return res_thread;
118 }
119
120 /** Bind the thread to the given core, if possible.
121  *
122  * If pthread_setaffinity_np is not usable on that (non-gnu) platform, this function does nothing.
123  */
124 int xbt_os_thread_bind(XBT_ATTRIB_UNUSED xbt_os_thread_t thread, XBT_ATTRIB_UNUSED int cpu)
125 {
126   int errcode = 0;
127 #if HAVE_PTHREAD_SETAFFINITY
128   pthread_t pthread = thread->t;
129   cpu_set_t cpuset;
130   CPU_ZERO(&cpuset);
131   CPU_SET(cpu, &cpuset);
132   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
133 #endif
134   return errcode;
135 }
136
137 void xbt_os_thread_setstacksize(int stack_size)
138 {
139   size_t alignment[] = {
140     xbt_pagesize,
141 #ifdef PTHREAD_STACK_MIN
142     PTHREAD_STACK_MIN,
143 #endif
144     0
145   };
146
147   xbt_assert(stack_size >= 0, "stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
148
149   size_t sz = stack_size;
150   int res = pthread_attr_setstacksize(&thread_attr, sz);
151
152   for (int i = 0; res == EINVAL && alignment[i] > 0; i++) {
153     /* Invalid size, try again with next multiple of alignment[i]. */
154     size_t rem = sz % alignment[i];
155     if (rem != 0 || sz == 0) {
156       size_t sz2 = sz - rem + alignment[i];
157       XBT_DEBUG("pthread_attr_setstacksize failed for %zu, try again with %zu", sz, sz2);
158       sz = sz2;
159       res = pthread_attr_setstacksize(&thread_attr, sz);
160     }
161   }
162
163   if (res == EINVAL)
164     XBT_WARN("invalid stack size (maybe too big): %zu", sz);
165   else if (res != 0)
166     XBT_WARN("unknown error %d in pthread stacksize setting: %zu", res, sz);
167 }
168
169 void xbt_os_thread_setguardsize(int guard_size)
170 {
171 #ifdef WIN32
172   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
173 #else
174   size_t sz = guard_size;
175   int res = pthread_attr_setguardsize(&thread_attr, sz);
176   if (res)
177     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zu", res, sz);
178 #endif
179 }
180
181 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
182 {
183   int errcode = pthread_join(thread->t, thread_return);
184
185   xbt_assert(errcode==0, "pthread_join failed: %s", strerror(errcode));
186   xbt_os_thread_free_thread_data(thread);
187 }
188
189 void xbt_os_thread_exit(int *retval)
190 {
191   pthread_exit(retval);
192 }
193
194 /****** mutex related functions ******/
195 typedef struct xbt_os_mutex_ {
196   pthread_mutex_t m;
197 } s_xbt_os_mutex_t;
198
199 #include <time.h>
200 #include <math.h>
201
202 xbt_os_mutex_t xbt_os_mutex_init(void)
203 {
204   pthread_mutexattr_t Attr;
205   pthread_mutexattr_init(&Attr);
206   pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
207
208   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
209   int errcode = pthread_mutex_init(&(res->m), &Attr);
210   xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
211
212   return res;
213 }
214
215 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
216 {
217   int errcode = pthread_mutex_lock(&(mutex->m));
218   xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
219 }
220
221 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
222 {
223   int errcode = pthread_mutex_unlock(&(mutex->m));
224   xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
225 }
226
227 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
228 {
229   if (!mutex)
230     return;
231
232   int errcode = pthread_mutex_destroy(&(mutex->m));
233   xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));
234   free(mutex);
235 }