Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[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-2015. The SimGrid Team.
6  * All rights reserved.                                                     */
7
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. */
10
11 #if defined(WIN32)
12 #elif defined(__MACH__) && defined(__APPLE__)
13 #include <stdint.h>
14 #include <sys/types.h>
15 #include <sys/sysctl.h>
16 #else
17 #include <unistd.h>
18 #endif
19
20 #include "src/internal_config.h"
21 #include "xbt/sysdep.h"
22 #include "xbt/ex.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 */
28
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt,
30                                 "Synchronization mechanism (OS-level)");
31
32 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
33 #include <pthread.h>
34 #include <limits.h>
35 #include <semaphore.h>
36
37 #ifdef CORE_BINDING
38 #define _GNU_SOURCE
39 #include <sched.h>
40 #endif
41
42 /* use named sempahore when sem_init() does not work */
43 #ifndef HAVE_SEM_INIT
44 static int next_sem_ID = 0;
45 static xbt_os_mutex_t next_sem_ID_lock;
46 #endif
47
48 typedef struct xbt_os_thread_ {
49   pthread_t t;
50   int detached;
51   char *name;
52   void *param;
53   pvoid_f_pvoid_t start_routine;
54   xbt_running_ctx_t *running_ctx;
55   void *extra_data;
56 } s_xbt_os_thread_t;
57 static xbt_os_thread_t main_thread = NULL;
58
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;
62
63 /* defaults attribute for pthreads */
64 //FIXME: find where to put this
65 static pthread_attr_t thread_attr;
66
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)
69 {
70   if (thread == main_thread)    /* just killed main thread */
71     main_thread = NULL;
72
73   free(thread->running_ctx);
74   free(thread->name);
75   free(thread);
76 }
77
78 /* callback: context fetching */
79 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
80 {
81   return xbt_os_thread_self()->running_ctx;
82 }
83
84 /* callback: termination */
85 static void _os_thread_ex_terminate(xbt_ex_t * e)
86 {
87   xbt_ex_display(e);
88   xbt_abort();
89   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
90 }
91
92 void xbt_os_thread_mod_preinit(void)
93 {
94   int errcode;
95
96   if (thread_mod_inited)
97     return;
98
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");
102   
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);
112
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)");
116   
117   __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
118   __xbt_ex_terminate = _os_thread_ex_terminate;
119
120   pthread_attr_init(&thread_attr);
121
122   thread_mod_inited = 1;
123
124 #ifndef HAVE_SEM_INIT
125   next_sem_ID_lock = xbt_os_mutex_init();
126 #endif
127
128 }
129
130 void xbt_os_thread_mod_postexit(void)
131 {
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 */
134   //   int errcode;
135
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);
139   free(main_thread);
140   main_thread = NULL;
141   thread_mod_inited = 0;
142 #ifndef HAVE_SEM_INIT
143   xbt_os_mutex_destroy(next_sem_ID_lock);
144 #endif
145
146   /* Restore the default exception setup */
147   __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
148   __xbt_ex_terminate = &__xbt_ex_terminate_default;
149 }
150
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))
154 {
155 #ifdef WIN32
156   THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
157 #else
158   return pthread_atfork(prepare, parent, child);
159 #endif
160 }
161
162 static void *wrapper_start_routine(void *s)
163 {
164   xbt_os_thread_t t = s;
165   int errcode;
166
167   if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
168     THROWF(system_error, errcode,
169            "pthread_setspecific failed for xbt_self_thread_key");
170
171   void *res = t->start_routine(t->param);
172   if (t->detached)
173     xbt_os_thread_free_thread_data(t);
174   return res;
175 }
176
177
178 xbt_os_thread_t xbt_os_thread_create(const char *name,
179                                      pvoid_f_pvoid_t start_routine,
180                                      void *param,
181                                      void *extra_data)
182 {
183   int errcode;
184
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;
193   
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));
198
199
200
201   return res_thread;
202 }
203
204
205 #ifdef CORE_BINDING
206 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
207   pthread_t pthread = thread->t;
208   int errcode = 0;
209   cpu_set_t cpuset;
210   CPU_ZERO(&cpuset);
211   CPU_SET(cpu, &cpuset);
212   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
213   return errcode;
214 }
215 #endif
216
217 void xbt_os_thread_setstacksize(int stack_size)
218 {
219   size_t alignment[] = {
220     xbt_pagesize,
221 #ifdef PTHREAD_STACK_MIN
222     PTHREAD_STACK_MIN,
223 #endif
224     0
225   };
226   size_t sz;
227   int res;
228   int i;
229
230   if (stack_size < 0)
231     xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
232
233   sz = stack_size;
234   res = pthread_attr_setstacksize(&thread_attr, sz);
235
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",
242                 sz, sz2);
243       sz = sz2;
244       res = pthread_attr_setstacksize(&thread_attr, sz);
245     }
246   }
247
248   if (res == EINVAL)
249     XBT_WARN("invalid stack size (maybe too big): %zd", sz);
250   else if (res != 0)
251     XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
252 }
253
254 void xbt_os_thread_setguardsize(int guard_size)
255 {
256 #ifdef WIN32
257   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
258 #else
259   size_t sz = guard_size;
260   int res = pthread_attr_setguardsize(&thread_attr, sz);
261   if (res)
262     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
263 #endif
264 }
265
266 const char *xbt_os_thread_name(xbt_os_thread_t t)
267 {
268   return t->name;
269 }
270
271 const char *xbt_os_thread_self_name(void)
272 {
273   xbt_os_thread_t me = xbt_os_thread_self();
274   return me ? me->name : "main";
275 }
276
277 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
278 {
279
280   int errcode;
281
282   if ((errcode = pthread_join(thread->t, thread_return)))
283     THROWF(system_error, errcode, "pthread_join failed: %s",
284            strerror(errcode));
285   xbt_os_thread_free_thread_data(thread);
286 }
287
288 void xbt_os_thread_exit(int *retval)
289 {
290   pthread_exit(retval);
291 }
292
293 xbt_os_thread_t xbt_os_thread_self(void)
294 {
295   if (!thread_mod_inited)
296     return NULL;
297
298   return pthread_getspecific(xbt_self_thread_key);
299 }
300
301 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
302
303   int errcode;
304   if ((errcode = pthread_key_create(key, NULL)))
305     THROWF(system_error, errcode, "pthread_key_create failed");
306 }
307
308 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
309
310   int errcode;
311   if ((errcode = pthread_setspecific(key, value)))
312     THROWF(system_error, errcode, "pthread_setspecific failed");
313 }
314
315 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
316   return pthread_getspecific(key);
317 }
318
319 void xbt_os_thread_detach(xbt_os_thread_t thread)
320 {
321   thread->detached = 1;
322   pthread_detach(thread->t);
323 }
324
325 #include <sched.h>
326 void xbt_os_thread_yield(void)
327 {
328   sched_yield();
329 }
330
331 void xbt_os_thread_cancel(xbt_os_thread_t t)
332 {
333   pthread_cancel(t->t);
334 }
335
336 /****** mutex related functions ******/
337 typedef struct xbt_os_mutex_ {
338   /* KEEP IT IN SYNC WITH xbt_thread.c */
339   pthread_mutex_t m;
340 } s_xbt_os_mutex_t;
341
342 #include <time.h>
343 #include <math.h>
344
345 xbt_os_mutex_t xbt_os_mutex_init(void)
346 {
347   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
348   int errcode;
349
350   if ((errcode = pthread_mutex_init(&(res->m), NULL)))
351     THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
352            strerror(errcode));
353
354   return res;
355 }
356
357 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
358 {
359   int errcode;
360
361   if ((errcode = pthread_mutex_lock(&(mutex->m))))
362     THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
363            mutex, strerror(errcode));
364 }
365
366
367 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
368 {
369   int errcode;
370
371   if (delay < 0) {
372     xbt_os_mutex_acquire(mutex);
373
374   } else if (delay == 0) {
375     errcode = pthread_mutex_trylock(&(mutex->m));
376
377     switch (errcode) {
378     case 0:
379       return;
380     case ETIMEDOUT:
381       THROWF(timeout_error, 0, "mutex %p not ready", mutex);
382     default:
383       THROWF(system_error, errcode,
384              "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
385              strerror(errcode));
386     }
387
388
389   } else {
390
391 #ifdef HAVE_MUTEX_TIMEDLOCK
392     struct timespec ts_end;
393     double end = delay + xbt_os_time();
394
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);
398
399     errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
400
401 #else                           /* Well, let's reimplement it since those lazy libc dudes didn't */
402     double start = xbt_os_time();
403     do {
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);
408
409     if (errcode == EBUSY)
410       errcode = ETIMEDOUT;
411
412 #endif                          /* HAVE_MUTEX_TIMEDLOCK */
413
414     switch (errcode) {
415     case 0:
416       return;
417
418     case ETIMEDOUT:
419       THROWF(timeout_error, delay,
420              "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
421
422     default:
423       THROWF(system_error, errcode,
424              "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
425              strerror(errcode));
426     }
427   }
428 }
429
430 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
431 {
432   int errcode;
433
434   if ((errcode = pthread_mutex_unlock(&(mutex->m))))
435     THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
436            mutex, strerror(errcode));
437 }
438
439 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
440 {
441   int errcode;
442
443   if (!mutex)
444     return;
445
446   if ((errcode = pthread_mutex_destroy(&(mutex->m))))
447     THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
448            mutex, strerror(errcode));
449   free(mutex);
450 }
451
452 /***** condition related functions *****/
453 typedef struct xbt_os_cond_ {
454   /* KEEP IT IN SYNC WITH xbt_thread.c */
455   pthread_cond_t c;
456 } s_xbt_os_cond_t;
457
458 xbt_os_cond_t xbt_os_cond_init(void)
459 {
460   xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
461   int errcode;
462   if ((errcode = pthread_cond_init(&(res->c), NULL)))
463     THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
464            strerror(errcode));
465
466   return res;
467 }
468
469 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
470 {
471   int errcode;
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));
475 }
476
477
478 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
479                            double delay)
480 {
481   int errcode;
482   struct timespec ts_end;
483   double end = delay + xbt_os_time();
484
485   if (delay < 0) {
486     xbt_os_cond_wait(cond, mutex);
487   } else {
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),
491            &ts_end);
492     switch ((errcode =
493              pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
494     case 0:
495       return;
496     case ETIMEDOUT:
497       THROWF(timeout_error, errcode,
498              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
499              cond, mutex, delay);
500     default:
501       THROWF(system_error, errcode,
502              "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
503              delay, strerror(errcode));
504     }
505   }
506 }
507
508 void xbt_os_cond_signal(xbt_os_cond_t cond)
509 {
510   int errcode;
511   if ((errcode = pthread_cond_signal(&(cond->c))))
512     THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
513            cond, strerror(errcode));
514 }
515
516 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
517 {
518   int errcode;
519   if ((errcode = pthread_cond_broadcast(&(cond->c))))
520     THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
521            cond, strerror(errcode));
522 }
523
524 void xbt_os_cond_destroy(xbt_os_cond_t cond)
525 {
526   int errcode;
527
528   if (!cond)
529     return;
530
531   if ((errcode = pthread_cond_destroy(&(cond->c))))
532     THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
533            cond, strerror(errcode));
534   free(cond);
535 }
536
537 void *xbt_os_thread_getparam(void)
538 {
539   xbt_os_thread_t t = xbt_os_thread_self();
540   return t ? t->param : NULL;
541 }
542
543 typedef struct xbt_os_sem_ {
544 #ifndef HAVE_SEM_INIT
545   char *name;
546 #endif
547   sem_t s;
548   sem_t *ps;
549 } s_xbt_os_sem_t;
550
551 #ifndef SEM_FAILED
552 #define SEM_FAILED (-1)
553 #endif
554
555 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
556 {
557   xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
558
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
562    */
563 #ifdef HAVE_SEM_INIT
564   if (sem_init(&(res->s), 0, value) != 0)
565     THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
566   res->ps = &(res->s);
567
568 #else                           /* damn, no sem_init(). Reimplement it */
569
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);
573
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);
579   }
580   if (res->ps == (sem_t *) SEM_FAILED)
581     THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
582
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",
586            strerror(errno));
587
588 #endif
589
590   return res;
591 }
592
593 void xbt_os_sem_acquire(xbt_os_sem_t sem)
594 {
595   if (!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));
599 }
600
601 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
602 {
603   int errcode;
604
605   if (!sem)
606     THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
607
608   if (delay < 0) {
609     xbt_os_sem_acquire(sem);
610   } else if (delay == 0) {
611     errcode = sem_trywait(sem->ps);
612
613     switch (errcode) {
614     case 0:
615       return;
616     case ETIMEDOUT:
617       THROWF(timeout_error, 0, "semaphore %p not ready", sem);
618     default:
619       THROWF(system_error, errcode,
620              "xbt_os_sem_timedacquire(%p) failed: %s", sem,
621              strerror(errcode));
622     }
623
624   } else {
625 #ifdef HAVE_SEM_WAIT
626     struct timespec ts_end;
627     double end = delay + xbt_os_time();
628
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);
633
634 #else                           /* Okay, reimplement this function then */
635     double start = xbt_os_time();
636     do {
637       errcode = sem_trywait(sem->ps);
638       if (errcode == EBUSY)
639         xbt_os_thread_yield();
640     } while (errcode == EBUSY && xbt_os_time() - start < delay);
641
642     if (errcode == EBUSY)
643       errcode = ETIMEDOUT;
644 #endif
645
646     switch (errcode) {
647     case 0:
648       return;
649
650     case ETIMEDOUT:
651       THROWF(timeout_error, delay,
652              "semaphore %p wasn't signaled before timeout (%f)", sem,
653              delay);
654
655     default:
656       THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
657              delay, strerror(errcode));
658     }
659   }
660 }
661
662 void xbt_os_sem_release(xbt_os_sem_t sem)
663 {
664   if (!sem)
665     THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
666
667   if (sem_post(sem->ps) < 0)
668     THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
669 }
670
671 void xbt_os_sem_destroy(xbt_os_sem_t sem)
672 {
673   if (!sem)
674     THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
675
676 #ifdef HAVE_SEM_INIT
677   if (sem_destroy(sem->ps) < 0)
678     THROWF(system_error, errno, "sem_destroy() failed: %s",
679            strerror(errno));
680 #else
681   if (sem_close(sem->ps) < 0)
682     THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
683   xbt_free(sem->name);
684
685 #endif
686   xbt_free(sem);
687 }
688
689 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
690 {
691   if (!sem)
692     THROWF(arg_error, EINVAL,
693            "Cannot get the value of the NULL semaphore");
694
695   if (sem_getvalue(&(sem->s), svalue) < 0)
696     THROWF(system_error, errno, "sem_getvalue() failed: %s",
697            strerror(errno));
698 }
699
700
701 /** @brief Returns the amount of cores on the current host */
702 int xbt_os_get_numcores(void) {
703 #ifdef WIN32
704     SYSTEM_INFO sysinfo;
705     GetSystemInfo(&sysinfo);
706     return sysinfo.dwNumberOfProcessors;
707 #elif defined(__APPLE__) && defined(__MACH__)
708     int nm[2];
709     size_t len = 4;
710     uint32_t count;
711
712     nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
713     sysctl(nm, 2, &count, &len, NULL, 0);
714
715     if(count < 1) {
716         nm[1] = HW_NCPU;
717         sysctl(nm, 2, &count, &len, NULL, 0);
718         if(count < 1) { count = 1; }
719     }
720     return count;
721 #else
722     return sysconf(_SC_NPROCESSORS_ONLN);
723 #endif
724 }
725
726
727 /***** reentrant mutexes *****/
728 typedef struct xbt_os_rmutex_ {
729   xbt_os_mutex_t mutex;
730   xbt_os_thread_t owner;
731   int count;
732 } s_xbt_os_rmutex_t;
733
734 void xbt_os_thread_set_extra_data(void *data)
735 {
736   xbt_os_thread_self()->extra_data = data;
737 }
738
739 void *xbt_os_thread_get_extra_data(void)
740 {
741   xbt_os_thread_t thread = xbt_os_thread_self();
742   if (thread)
743     return xbt_os_thread_self()->extra_data;
744   else
745     return NULL;
746 }
747
748 xbt_os_rmutex_t xbt_os_rmutex_init(void)
749 {
750   xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
751   rmutex->mutex = xbt_os_mutex_init();
752   rmutex->owner = NULL;
753   rmutex->count = 0;
754   return rmutex;
755 }
756
757 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
758 {
759   xbt_os_thread_t self = xbt_os_thread_self();
760
761   if (self == NULL) {
762     /* the thread module is not initialized yet */
763     rmutex->owner = NULL;
764     return;
765   }
766
767   if (self != rmutex->owner) {
768     xbt_os_mutex_acquire(rmutex->mutex);
769     rmutex->owner = self;
770     rmutex->count = 1;
771   } else {
772     rmutex->count++;
773  }
774 }
775
776 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
777 {
778   if (rmutex->owner == NULL) {
779     /* the thread module was not initialized */
780     return;
781   }
782
783   xbt_assert(rmutex->owner == xbt_os_thread_self());
784
785   if (--rmutex->count == 0) {
786     rmutex->owner = NULL;
787     xbt_os_mutex_release(rmutex->mutex);
788   }
789 }
790
791 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
792 {
793   xbt_os_mutex_destroy(rmutex->mutex);
794   xbt_free(rmutex);
795 }