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 #ifndef _XBT_WIN32
34
35 #include <pthread.h>
36 #include <limits.h>
37 #include <semaphore.h>
38
39 #ifdef CORE_BINDING
40 #define _GNU_SOURCE
41 #include <sched.h>
42 #endif
43
44 /* use named sempahore when sem_init() does not work */
45 #ifndef HAVE_SEM_INIT
46 static int next_sem_ID = 0;
47 static xbt_os_mutex_t next_sem_ID_lock;
48 #endif
49
50 typedef struct xbt_os_thread_ {
51   pthread_t t;
52   int detached;
53   char *name;
54   void *param;
55   pvoid_f_pvoid_t start_routine;
56   xbt_running_ctx_t *running_ctx;
57   void *extra_data;
58 } s_xbt_os_thread_t;
59 static xbt_os_thread_t main_thread = NULL;
60
61 /* thread-specific data containing the xbt_os_thread_t structure */
62 static pthread_key_t xbt_self_thread_key;
63 static int thread_mod_inited = 0;
64
65 /* defaults attribute for pthreads */
66 //FIXME: find where to put this
67 static pthread_attr_t thread_attr;
68
69 /* frees the xbt_os_thread_t corresponding to the current thread */
70 static void xbt_os_thread_free_thread_data(xbt_os_thread_t thread)
71 {
72   if (thread == main_thread)    /* just killed main thread */
73     main_thread = NULL;
74
75   free(thread->running_ctx);
76   free(thread->name);
77   free(thread);
78 }
79
80 /* callback: context fetching */
81 static xbt_running_ctx_t *_os_thread_get_running_ctx(void)
82 {
83   return xbt_os_thread_self()->running_ctx;
84 }
85
86 /* callback: termination */
87 static void _os_thread_ex_terminate(xbt_ex_t * e)
88 {
89   xbt_ex_display(e);
90   xbt_abort();
91   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
92 }
93
94 void xbt_os_thread_mod_preinit(void)
95 {
96   int errcode;
97
98   if (thread_mod_inited)
99     return;
100
101   if ((errcode = pthread_key_create(&xbt_self_thread_key, NULL)))
102     THROWF(system_error, errcode,
103            "pthread_key_create failed for xbt_self_thread_key");
104   
105   main_thread = xbt_new(s_xbt_os_thread_t, 1);
106   main_thread->name = NULL;
107   main_thread->detached = 0;
108   main_thread->name = (char *) "main";
109   main_thread->param = NULL;
110   main_thread->start_routine = NULL;
111   main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
112   main_thread->extra_data = NULL;
113   XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
114
115   if ((errcode = pthread_setspecific(xbt_self_thread_key, main_thread)))
116     THROWF(system_error, errcode,
117            "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
118   
119   __xbt_running_ctx_fetch = _os_thread_get_running_ctx;
120   __xbt_ex_terminate = _os_thread_ex_terminate;
121
122   pthread_attr_init(&thread_attr);
123
124   thread_mod_inited = 1;
125
126 #ifndef HAVE_SEM_INIT
127   next_sem_ID_lock = xbt_os_mutex_init();
128 #endif
129
130 }
131
132 void xbt_os_thread_mod_postexit(void)
133 {
134   /* FIXME: don't try to free our key on shutdown.
135      Valgrind detects no leak if we don't, and whine if we try to */
136   //   int errcode;
137
138   //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
139   //     THROWF(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
140   free(main_thread->running_ctx);
141   free(main_thread);
142   main_thread = NULL;
143   thread_mod_inited = 0;
144 #ifndef HAVE_SEM_INIT
145   xbt_os_mutex_destroy(next_sem_ID_lock);
146 #endif
147
148   /* Restore the default exception setup */
149   __xbt_running_ctx_fetch = &__xbt_ex_ctx_default;
150   __xbt_ex_terminate = &__xbt_ex_terminate_default;
151 }
152
153 /* this function is critical to tesh+mmalloc, don't mess with it */
154 int xbt_os_thread_atfork(void (*prepare)(void),
155                          void (*parent)(void), void (*child)(void))
156 {
157 #ifdef WIN32
158   THROW_UNIMPLEMENTED; //pthread_atfork is not implemented in pthread.h on windows
159 #else
160   return pthread_atfork(prepare, parent, child);
161 #endif
162 }
163
164 static void *wrapper_start_routine(void *s)
165 {
166   xbt_os_thread_t t = s;
167   int errcode;
168
169   if ((errcode = pthread_setspecific(xbt_self_thread_key, t)))
170     THROWF(system_error, errcode,
171            "pthread_setspecific failed for xbt_self_thread_key");
172
173   void *res = t->start_routine(t->param);
174   if (t->detached)
175     xbt_os_thread_free_thread_data(t);
176   return res;
177 }
178
179
180 xbt_os_thread_t xbt_os_thread_create(const char *name,
181                                      pvoid_f_pvoid_t start_routine,
182                                      void *param,
183                                      void *extra_data)
184 {
185   int errcode;
186
187   xbt_os_thread_t res_thread = xbt_new(s_xbt_os_thread_t, 1);
188   res_thread->detached = 0;
189   res_thread->name = xbt_strdup(name);
190   res_thread->start_routine = start_routine;
191   res_thread->param = param;
192   res_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
193   XBT_RUNNING_CTX_INITIALIZE(res_thread->running_ctx);
194   res_thread->extra_data = extra_data;
195   
196   if ((errcode = pthread_create(&(res_thread->t), &thread_attr,
197                                 wrapper_start_routine, res_thread)))
198     THROWF(system_error, errcode,
199            "pthread_create failed: %s", strerror(errcode));
200
201
202
203   return res_thread;
204 }
205
206
207 #ifdef CORE_BINDING
208 int xbt_os_thread_bind(xbt_os_thread_t thread, int cpu){
209   pthread_t pthread = thread->t;
210   int errcode = 0;
211   cpu_set_t cpuset;
212   CPU_ZERO(&cpuset);
213   CPU_SET(cpu, &cpuset);
214   errcode = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset);
215   return errcode;
216 }
217 #endif
218
219 void xbt_os_thread_setstacksize(int stack_size)
220 {
221   size_t alignment[] = {
222     xbt_pagesize,
223 #ifdef PTHREAD_STACK_MIN
224     PTHREAD_STACK_MIN,
225 #endif
226     0
227   };
228   size_t sz;
229   int res;
230   int i;
231
232   if (stack_size < 0)
233     xbt_die("stack size %d is negative, maybe it exceeds MAX_INT?", stack_size);
234
235   sz = stack_size;
236   res = pthread_attr_setstacksize(&thread_attr, sz);
237
238   for (i = 0; res == EINVAL && alignment[i] > 0; i++) {
239     /* Invalid size, try again with next multiple of alignment[i]. */
240     size_t rem = sz % alignment[i];
241     if (rem != 0 || sz == 0) {
242       size_t sz2 = sz - rem + alignment[i];
243       XBT_DEBUG("pthread_attr_setstacksize failed for %zd, try again with %zd",
244                 sz, sz2);
245       sz = sz2;
246       res = pthread_attr_setstacksize(&thread_attr, sz);
247     }
248   }
249
250   if (res == EINVAL)
251     XBT_WARN("invalid stack size (maybe too big): %zd", sz);
252   else if (res != 0)
253     XBT_WARN("unknown error %d in pthread stacksize setting: %zd", res, sz);
254 }
255
256 void xbt_os_thread_setguardsize(int guard_size)
257 {
258 #ifdef WIN32
259   THROW_UNIMPLEMENTED; //pthread_attr_setguardsize is not implemented in pthread.h on windows
260 #else
261   size_t sz = guard_size;
262   int res = pthread_attr_setguardsize(&thread_attr, sz);
263   if (res)
264     XBT_WARN("pthread_attr_setguardsize failed (%d) for size: %zd", res, sz);
265 #endif
266 }
267
268 const char *xbt_os_thread_name(xbt_os_thread_t t)
269 {
270   return t->name;
271 }
272
273 const char *xbt_os_thread_self_name(void)
274 {
275   xbt_os_thread_t me = xbt_os_thread_self();
276   return me ? me->name : "main";
277 }
278
279 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
280 {
281
282   int errcode;
283
284   if ((errcode = pthread_join(thread->t, thread_return)))
285     THROWF(system_error, errcode, "pthread_join failed: %s",
286            strerror(errcode));
287   xbt_os_thread_free_thread_data(thread);
288 }
289
290 void xbt_os_thread_exit(int *retval)
291 {
292   pthread_exit(retval);
293 }
294
295 xbt_os_thread_t xbt_os_thread_self(void)
296 {
297   if (!thread_mod_inited)
298     return NULL;
299
300   return pthread_getspecific(xbt_self_thread_key);
301 }
302
303 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
304
305   int errcode;
306   if ((errcode = pthread_key_create(key, NULL)))
307     THROWF(system_error, errcode, "pthread_key_create failed");
308 }
309
310 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
311
312   int errcode;
313   if ((errcode = pthread_setspecific(key, value)))
314     THROWF(system_error, errcode, "pthread_setspecific failed");
315 }
316
317 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
318   return pthread_getspecific(key);
319 }
320
321 void xbt_os_thread_detach(xbt_os_thread_t thread)
322 {
323   thread->detached = 1;
324   pthread_detach(thread->t);
325 }
326
327 #include <sched.h>
328 void xbt_os_thread_yield(void)
329 {
330   sched_yield();
331 }
332
333 void xbt_os_thread_cancel(xbt_os_thread_t t)
334 {
335   pthread_cancel(t->t);
336 }
337
338 /****** mutex related functions ******/
339 typedef struct xbt_os_mutex_ {
340   /* KEEP IT IN SYNC WITH xbt_thread.c */
341   pthread_mutex_t m;
342 } s_xbt_os_mutex_t;
343
344 #include <time.h>
345 #include <math.h>
346
347 xbt_os_mutex_t xbt_os_mutex_init(void)
348 {
349   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
350   int errcode;
351
352   if ((errcode = pthread_mutex_init(&(res->m), NULL)))
353     THROWF(system_error, errcode, "pthread_mutex_init() failed: %s",
354            strerror(errcode));
355
356   return res;
357 }
358
359 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
360 {
361   int errcode;
362
363   if ((errcode = pthread_mutex_lock(&(mutex->m))))
364     THROWF(system_error, errcode, "pthread_mutex_lock(%p) failed: %s",
365            mutex, strerror(errcode));
366 }
367
368
369 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
370 {
371   int errcode;
372
373   if (delay < 0) {
374     xbt_os_mutex_acquire(mutex);
375
376   } else if (delay == 0) {
377     errcode = pthread_mutex_trylock(&(mutex->m));
378
379     switch (errcode) {
380     case 0:
381       return;
382     case ETIMEDOUT:
383       THROWF(timeout_error, 0, "mutex %p not ready", mutex);
384     default:
385       THROWF(system_error, errcode,
386              "xbt_os_mutex_timedacquire(%p) failed: %s", mutex,
387              strerror(errcode));
388     }
389
390
391   } else {
392
393 #ifdef HAVE_MUTEX_TIMEDLOCK
394     struct timespec ts_end;
395     double end = delay + xbt_os_time();
396
397     ts_end.tv_sec = (time_t) floor(end);
398     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
399     XBT_DEBUG("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
400
401     errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
402
403 #else                           /* Well, let's reimplement it since those lazy libc dudes didn't */
404     double start = xbt_os_time();
405     do {
406       errcode = pthread_mutex_trylock(&(mutex->m));
407       if (errcode == EBUSY)
408         xbt_os_thread_yield();
409     } while (errcode == EBUSY && xbt_os_time() - start < delay);
410
411     if (errcode == EBUSY)
412       errcode = ETIMEDOUT;
413
414 #endif                          /* HAVE_MUTEX_TIMEDLOCK */
415
416     switch (errcode) {
417     case 0:
418       return;
419
420     case ETIMEDOUT:
421       THROWF(timeout_error, delay,
422              "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
423
424     default:
425       THROWF(system_error, errcode,
426              "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
427              strerror(errcode));
428     }
429   }
430 }
431
432 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
433 {
434   int errcode;
435
436   if ((errcode = pthread_mutex_unlock(&(mutex->m))))
437     THROWF(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
438            mutex, strerror(errcode));
439 }
440
441 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
442 {
443   int errcode;
444
445   if (!mutex)
446     return;
447
448   if ((errcode = pthread_mutex_destroy(&(mutex->m))))
449     THROWF(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
450            mutex, strerror(errcode));
451   free(mutex);
452 }
453
454 /***** condition related functions *****/
455 typedef struct xbt_os_cond_ {
456   /* KEEP IT IN SYNC WITH xbt_thread.c */
457   pthread_cond_t c;
458 } s_xbt_os_cond_t;
459
460 xbt_os_cond_t xbt_os_cond_init(void)
461 {
462   xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
463   int errcode;
464   if ((errcode = pthread_cond_init(&(res->c), NULL)))
465     THROWF(system_error, errcode, "pthread_cond_init() failed: %s",
466            strerror(errcode));
467
468   return res;
469 }
470
471 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
472 {
473   int errcode;
474   if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
475     THROWF(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
476            cond, mutex, strerror(errcode));
477 }
478
479
480 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
481                            double delay)
482 {
483   int errcode;
484   struct timespec ts_end;
485   double end = delay + xbt_os_time();
486
487   if (delay < 0) {
488     xbt_os_cond_wait(cond, mutex);
489   } else {
490     ts_end.tv_sec = (time_t) floor(end);
491     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
492     XBT_DEBUG("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
493            &ts_end);
494     switch ((errcode =
495              pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
496     case 0:
497       return;
498     case ETIMEDOUT:
499       THROWF(timeout_error, errcode,
500              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
501              cond, mutex, delay);
502     default:
503       THROWF(system_error, errcode,
504              "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
505              delay, strerror(errcode));
506     }
507   }
508 }
509
510 void xbt_os_cond_signal(xbt_os_cond_t cond)
511 {
512   int errcode;
513   if ((errcode = pthread_cond_signal(&(cond->c))))
514     THROWF(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
515            cond, strerror(errcode));
516 }
517
518 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
519 {
520   int errcode;
521   if ((errcode = pthread_cond_broadcast(&(cond->c))))
522     THROWF(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
523            cond, strerror(errcode));
524 }
525
526 void xbt_os_cond_destroy(xbt_os_cond_t cond)
527 {
528   int errcode;
529
530   if (!cond)
531     return;
532
533   if ((errcode = pthread_cond_destroy(&(cond->c))))
534     THROWF(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
535            cond, strerror(errcode));
536   free(cond);
537 }
538
539 void *xbt_os_thread_getparam(void)
540 {
541   xbt_os_thread_t t = xbt_os_thread_self();
542   return t ? t->param : NULL;
543 }
544
545 typedef struct xbt_os_sem_ {
546 #ifndef HAVE_SEM_INIT
547   char *name;
548 #endif
549   sem_t s;
550   sem_t *ps;
551 } s_xbt_os_sem_t;
552
553 #ifndef SEM_FAILED
554 #define SEM_FAILED (-1)
555 #endif
556
557 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
558 {
559   xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
560
561   /* On some systems (MAC OS X), only the stub of sem_init is to be found.
562    * Any attempt to use it leads to ENOSYS (function not implemented).
563    * If such a prehistoric system is detected, do the job with sem_open instead
564    */
565 #ifdef HAVE_SEM_INIT
566   if (sem_init(&(res->s), 0, value) != 0)
567     THROWF(system_error, errno, "sem_init() failed: %s", strerror(errno));
568   res->ps = &(res->s);
569
570 #else                           /* damn, no sem_init(). Reimplement it */
571
572   xbt_os_mutex_acquire(next_sem_ID_lock);
573   res->name = bprintf("/%d", ++next_sem_ID);
574   xbt_os_mutex_release(next_sem_ID_lock);
575
576   res->ps = sem_open(res->name, O_CREAT, 0644, value);
577   if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
578     /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
579     res->name[13] = '\0';
580     res->ps = sem_open(res->name, O_CREAT, 0644, value);
581   }
582   if (res->ps == (sem_t *) SEM_FAILED)
583     THROWF(system_error, errno, "sem_open() failed: %s", strerror(errno));
584
585   /* Remove the name from the semaphore namespace: we never join on it */
586   if (sem_unlink(res->name) < 0)
587     THROWF(system_error, errno, "sem_unlink() failed: %s",
588            strerror(errno));
589
590 #endif
591
592   return res;
593 }
594
595 void xbt_os_sem_acquire(xbt_os_sem_t sem)
596 {
597   if (!sem)
598     THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
599   if (sem_wait(sem->ps) < 0)
600     THROWF(system_error, errno, "sem_wait() failed: %s", strerror(errno));
601 }
602
603 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
604 {
605   int errcode;
606
607   if (!sem)
608     THROWF(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
609
610   if (delay < 0) {
611     xbt_os_sem_acquire(sem);
612   } else if (delay == 0) {
613     errcode = sem_trywait(sem->ps);
614
615     switch (errcode) {
616     case 0:
617       return;
618     case ETIMEDOUT:
619       THROWF(timeout_error, 0, "semaphore %p not ready", sem);
620     default:
621       THROWF(system_error, errcode,
622              "xbt_os_sem_timedacquire(%p) failed: %s", sem,
623              strerror(errcode));
624     }
625
626   } else {
627 #ifdef HAVE_SEM_WAIT
628     struct timespec ts_end;
629     double end = delay + xbt_os_time();
630
631     ts_end.tv_sec = (time_t) floor(end);
632     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
633     XBT_DEBUG("sem_timedwait(%p,%p)", sem->ps, &ts_end);
634     errcode = sem_timedwait(sem->s, &ts_end);
635
636 #else                           /* Okay, reimplement this function then */
637     double start = xbt_os_time();
638     do {
639       errcode = sem_trywait(sem->ps);
640       if (errcode == EBUSY)
641         xbt_os_thread_yield();
642     } while (errcode == EBUSY && xbt_os_time() - start < delay);
643
644     if (errcode == EBUSY)
645       errcode = ETIMEDOUT;
646 #endif
647
648     switch (errcode) {
649     case 0:
650       return;
651
652     case ETIMEDOUT:
653       THROWF(timeout_error, delay,
654              "semaphore %p wasn't signaled before timeout (%f)", sem,
655              delay);
656
657     default:
658       THROWF(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
659              delay, strerror(errcode));
660     }
661   }
662 }
663
664 void xbt_os_sem_release(xbt_os_sem_t sem)
665 {
666   if (!sem)
667     THROWF(arg_error, EINVAL, "Cannot release of the NULL semaphore");
668
669   if (sem_post(sem->ps) < 0)
670     THROWF(system_error, errno, "sem_post() failed: %s", strerror(errno));
671 }
672
673 void xbt_os_sem_destroy(xbt_os_sem_t sem)
674 {
675   if (!sem)
676     THROWF(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
677
678 #ifdef HAVE_SEM_INIT
679   if (sem_destroy(sem->ps) < 0)
680     THROWF(system_error, errno, "sem_destroy() failed: %s",
681            strerror(errno));
682 #else
683   if (sem_close(sem->ps) < 0)
684     THROWF(system_error, errno, "sem_close() failed: %s", strerror(errno));
685   xbt_free(sem->name);
686
687 #endif
688   xbt_free(sem);
689 }
690
691 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
692 {
693   if (!sem)
694     THROWF(arg_error, EINVAL,
695            "Cannot get the value of the NULL semaphore");
696
697   if (sem_getvalue(&(sem->s), svalue) < 0)
698     THROWF(system_error, errno, "sem_getvalue() failed: %s",
699            strerror(errno));
700 }
701
702 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
703
704 #elif defined(_XBT_WIN32)
705
706 #include <math.h>
707
708 typedef struct xbt_os_thread_ {
709   char *name;
710   HANDLE handle;                /* the win thread handle        */
711   unsigned long id;             /* the win thread id            */
712   pvoid_f_pvoid_t start_routine;
713   void *param;
714   void *extra_data;
715 } s_xbt_os_thread_t;
716
717 /* so we can specify the size of the stack of the threads */
718 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
719 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
720 #endif
721
722 /* the default size of the stack of the threads (in bytes)*/
723 #define XBT_DEFAULT_THREAD_STACK_SIZE  4096
724 static int stack_size=0;
725 /* key to the TLS containing the xbt_os_thread_t structure */
726 static unsigned long xbt_self_thread_key;
727
728 void xbt_os_thread_mod_preinit(void)
729 {
730   xbt_self_thread_key = TlsAlloc();
731
732   xbt_os_thread_t main_thread = xbt_new0(s_xbt_os_thread_t, 1);
733   main_thread->name = (char *) "main";
734   main_thread->start_routine = NULL;
735   main_thread->param = NULL;
736
737   if (!TlsSetValue(xbt_self_thread_key, main_thread))
738     THROWF(system_error, (int)GetLastError(),
739            "Impossible to set the SimGrid identity descriptor to the main thread (TlsSetValue() failed)");
740
741 }
742
743 void xbt_os_thread_mod_postexit(void)
744 {
745
746   if (!TlsFree(xbt_self_thread_key))
747     THROWF(system_error, (int) GetLastError(),
748            "TlsFree() failed to cleanup the thread submodule");
749 }
750
751 int xbt_os_thread_atfork(void (*prepare)(void),
752                          void (*parent)(void), void (*child)(void))
753 {
754   return 0;
755 }
756
757 static DWORD WINAPI wrapper_start_routine(void *s)
758 {
759   xbt_os_thread_t t = (xbt_os_thread_t) s;
760   DWORD *rv;
761
762   if (!TlsSetValue(xbt_self_thread_key, t))
763     THROWF(system_error, (int) GetLastError(),
764            "TlsSetValue of data describing the created thread failed");
765
766   rv = (DWORD *) ((t->start_routine) (t->param));
767
768   return rv ? *rv : 0;
769
770 }
771
772
773 xbt_os_thread_t xbt_os_thread_create(const char *name,
774                                      pvoid_f_pvoid_t start_routine,
775                                      void *param,
776                                      void *extra_data)
777 {
778
779   xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
780
781   t->name = xbt_strdup(name);
782   t->start_routine = start_routine;
783   t->param = param;
784   t->extra_data = extra_data;
785   t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
786                            (LPTHREAD_START_ROUTINE) wrapper_start_routine,
787                            t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
788
789   if (!t->handle) {
790     xbt_free(t);
791     THROWF(system_error, (int) GetLastError(), "CreateThread failed");
792   }
793
794   return t;
795 }
796
797 void xbt_os_thread_setstacksize(int size)
798 {
799   stack_size = size;
800 }
801
802 void xbt_os_thread_setguardsize(int size)
803 {
804   XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
805 }
806
807 const char *xbt_os_thread_name(xbt_os_thread_t t)
808 {
809   return t->name;
810 }
811
812 const char *xbt_os_thread_self_name(void)
813 {
814   xbt_os_thread_t t = xbt_os_thread_self();
815   return t ? t->name : "main";
816 }
817
818 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
819 {
820
821   if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
822     THROWF(system_error, (int) GetLastError(),
823            "WaitForSingleObject failed");
824
825   if (thread_return) {
826
827     if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
828       THROWF(system_error, (int) GetLastError(),
829              "GetExitCodeThread failed");
830   }
831
832   CloseHandle(thread->handle);
833
834   free(thread->name);
835
836   free(thread);
837 }
838
839 void xbt_os_thread_exit(int *retval)
840 {
841   if (retval)
842     ExitThread(*retval);
843   else
844     ExitThread(0);
845 }
846
847 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
848
849   *key = TlsAlloc();
850 }
851
852 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
853
854   if (!TlsSetValue(key, value))
855     THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
856 }
857
858 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
859   return TlsGetValue(key);
860 }
861
862 void xbt_os_thread_detach(xbt_os_thread_t thread)
863 {
864   THROW_UNIMPLEMENTED;
865 }
866
867
868 xbt_os_thread_t xbt_os_thread_self(void)
869 {
870   return TlsGetValue(xbt_self_thread_key);
871 }
872
873 void *xbt_os_thread_getparam(void)
874 {
875   xbt_os_thread_t t = xbt_os_thread_self();
876   return t->param;
877 }
878
879
880 void xbt_os_thread_yield(void)
881 {
882   Sleep(0);
883 }
884
885 void xbt_os_thread_cancel(xbt_os_thread_t t)
886 {
887   if (!TerminateThread(t->handle, 0))
888     THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
889 }
890
891 /****** mutex related functions ******/
892 typedef struct xbt_os_mutex_ {
893   /* KEEP IT IN SYNC WITH xbt_thread.c */
894   CRITICAL_SECTION lock;
895 } s_xbt_os_mutex_t;
896
897 xbt_os_mutex_t xbt_os_mutex_init(void)
898 {
899   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
900
901   /* initialize the critical section object */
902   InitializeCriticalSection(&(res->lock));
903
904   return res;
905 }
906
907 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
908 {
909   EnterCriticalSection(&mutex->lock);
910 }
911
912 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
913 {
914   THROW_UNIMPLEMENTED;
915 }
916
917 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
918 {
919
920   LeaveCriticalSection(&mutex->lock);
921
922 }
923
924 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
925 {
926
927   if (!mutex)
928     return;
929
930   DeleteCriticalSection(&mutex->lock);
931   free(mutex);
932 }
933
934 /***** condition related functions *****/
935 enum {                          /* KEEP IT IN SYNC WITH xbt_thread.c */
936   SIGNAL = 0,
937   BROADCAST = 1,
938   MAX_EVENTS = 2
939 };
940
941 typedef struct xbt_os_cond_ {
942   /* KEEP IT IN SYNC WITH xbt_thread.c */
943   HANDLE events[MAX_EVENTS];
944
945   unsigned int waiters_count;   /* the number of waiters                        */
946   CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
947 } s_xbt_os_cond_t;
948
949 xbt_os_cond_t xbt_os_cond_init(void)
950 {
951
952   xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
953
954   memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
955
956   /* initialize the critical section object */
957   InitializeCriticalSection(&res->waiters_count_lock);
958
959   res->waiters_count = 0;
960
961   /* Create an auto-reset event */
962   res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
963
964   if (!res->events[SIGNAL]) {
965     DeleteCriticalSection(&res->waiters_count_lock);
966     free(res);
967     THROWF(system_error, 0, "CreateEvent failed for the signals");
968   }
969
970   /* Create a manual-reset event. */
971   res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
972
973   if (!res->events[BROADCAST]) {
974
975     DeleteCriticalSection(&res->waiters_count_lock);
976     CloseHandle(res->events[SIGNAL]);
977     free(res);
978     THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
979   }
980
981   return res;
982 }
983
984 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
985 {
986
987   unsigned long wait_result;
988   int is_last_waiter;
989
990   /* lock the threads counter and increment it */
991   EnterCriticalSection(&cond->waiters_count_lock);
992   cond->waiters_count++;
993   LeaveCriticalSection(&cond->waiters_count_lock);
994
995   /* unlock the mutex associate with the condition */
996   LeaveCriticalSection(&mutex->lock);
997
998   /* wait for a signal (broadcast or no) */
999   wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
1000
1001   if (wait_result == WAIT_FAILED)
1002     THROWF(system_error, 0,
1003            "WaitForMultipleObjects failed, so we cannot wait on the condition");
1004
1005   /* we have a signal lock the condition */
1006   EnterCriticalSection(&cond->waiters_count_lock);
1007   cond->waiters_count--;
1008
1009   /* it's the last waiter or it's a broadcast ? */
1010   is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1011                     && (cond->waiters_count == 0));
1012
1013   LeaveCriticalSection(&cond->waiters_count_lock);
1014
1015   /* yes it's the last waiter or it's a broadcast
1016    * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1017    * by the system.
1018    */
1019   if (is_last_waiter)
1020     if (!ResetEvent(cond->events[BROADCAST]))
1021       THROWF(system_error, 0, "ResetEvent failed");
1022
1023   /* relock the mutex associated with the condition in accordance with the posix thread specification */
1024   EnterCriticalSection(&mutex->lock);
1025 }
1026
1027 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1028                            double delay)
1029 {
1030
1031   unsigned long wait_result = WAIT_TIMEOUT;
1032   int is_last_waiter;
1033   unsigned long end = (unsigned long) (delay * 1000);
1034
1035
1036   if (delay < 0) {
1037     xbt_os_cond_wait(cond, mutex);
1038   } else {
1039     XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1040            &(mutex->lock), end);
1041
1042     /* lock the threads counter and increment it */
1043     EnterCriticalSection(&cond->waiters_count_lock);
1044     cond->waiters_count++;
1045     LeaveCriticalSection(&cond->waiters_count_lock);
1046
1047     /* unlock the mutex associate with the condition */
1048     LeaveCriticalSection(&mutex->lock);
1049     /* wait for a signal (broadcast or no) */
1050
1051     wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1052
1053     switch (wait_result) {
1054     case WAIT_TIMEOUT:
1055       THROWF(timeout_error, GetLastError(),
1056              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1057              cond, mutex, delay);
1058     case WAIT_FAILED:
1059       THROWF(system_error, GetLastError(),
1060              "WaitForMultipleObjects failed, so we cannot wait on the condition");
1061     }
1062
1063     /* we have a signal lock the condition */
1064     EnterCriticalSection(&cond->waiters_count_lock);
1065     cond->waiters_count--;
1066
1067     /* it's the last waiter or it's a broadcast ? */
1068     is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1069                       && (cond->waiters_count == 0));
1070
1071     LeaveCriticalSection(&cond->waiters_count_lock);
1072
1073     /* yes it's the last waiter or it's a broadcast
1074      * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1075      * by the system.
1076      */
1077     if (is_last_waiter)
1078       if (!ResetEvent(cond->events[BROADCAST]))
1079         THROWF(system_error, 0, "ResetEvent failed");
1080
1081     /* relock the mutex associated with the condition in accordance with the posix thread specification */
1082     EnterCriticalSection(&mutex->lock);
1083   }
1084   /*THROW_UNIMPLEMENTED; */
1085 }
1086
1087 void xbt_os_cond_signal(xbt_os_cond_t cond)
1088 {
1089   int have_waiters;
1090
1091   EnterCriticalSection(&cond->waiters_count_lock);
1092   have_waiters = cond->waiters_count > 0;
1093   LeaveCriticalSection(&cond->waiters_count_lock);
1094
1095   if (have_waiters)
1096     if (!SetEvent(cond->events[SIGNAL]))
1097       THROWF(system_error, 0, "SetEvent failed");
1098
1099   xbt_os_thread_yield();
1100 }
1101
1102 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1103 {
1104   int have_waiters;
1105
1106   EnterCriticalSection(&cond->waiters_count_lock);
1107   have_waiters = cond->waiters_count > 0;
1108   LeaveCriticalSection(&cond->waiters_count_lock);
1109
1110   if (have_waiters)
1111     SetEvent(cond->events[BROADCAST]);
1112 }
1113
1114 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1115 {
1116   int error = 0;
1117
1118   if (!cond)
1119     return;
1120
1121   if (!CloseHandle(cond->events[SIGNAL]))
1122     error = 1;
1123
1124   if (!CloseHandle(cond->events[BROADCAST]))
1125     error = 1;
1126
1127   DeleteCriticalSection(&cond->waiters_count_lock);
1128
1129   xbt_free(cond);
1130
1131   if (error)
1132     THROWF(system_error, 0, "Error while destroying the condition");
1133 }
1134
1135 typedef struct xbt_os_sem_ {
1136   HANDLE h;
1137   unsigned int value;
1138   CRITICAL_SECTION value_lock;  /* protect access to value of the semaphore  */
1139 } s_xbt_os_sem_t;
1140
1141 #ifndef INT_MAX
1142 # define INT_MAX 32767          /* let's be safe by underestimating this value: this is for 16bits only */
1143 #endif
1144
1145 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1146 {
1147   xbt_os_sem_t res;
1148
1149   if (value > INT_MAX)
1150     THROWF(arg_error, value,
1151            "Semaphore initial value too big: %ud cannot be stored as a signed int",
1152            value);
1153
1154   res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1155
1156   if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1157     THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1158            strerror(GetLastError()));
1159     return NULL;
1160   }
1161
1162   res->value = value;
1163
1164   InitializeCriticalSection(&(res->value_lock));
1165
1166   return res;
1167 }
1168
1169 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1170 {
1171   if (!sem)
1172     THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1173
1174   /* wait failure */
1175   if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1176     THROWF(system_error, GetLastError(),
1177            "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1178   EnterCriticalSection(&(sem->value_lock));
1179   sem->value--;
1180   LeaveCriticalSection(&(sem->value_lock));
1181 }
1182
1183 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1184 {
1185   long seconds;
1186   long milliseconds;
1187   double end = timeout + xbt_os_time();
1188
1189   if (!sem)
1190     THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1191
1192   if (timeout < 0) {
1193     xbt_os_sem_acquire(sem);
1194   } else {                      /* timeout can be zero <-> try acquire ) */
1195
1196
1197     seconds = (long) floor(end);
1198     milliseconds = (long) ((end - seconds) * 1000);
1199     milliseconds += (seconds * 1000);
1200
1201     switch (WaitForSingleObject(sem->h, milliseconds)) {
1202     case WAIT_OBJECT_0:
1203       EnterCriticalSection(&(sem->value_lock));
1204       sem->value--;
1205       LeaveCriticalSection(&(sem->value_lock));
1206       return;
1207
1208     case WAIT_TIMEOUT:
1209       THROWF(timeout_error, GetLastError(),
1210              "semaphore %p wasn't signaled before timeout (%f)", sem,
1211              timeout);
1212       return;
1213
1214     default:
1215       THROWF(system_error, GetLastError(),
1216              "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1217              strerror(GetLastError()));
1218     }
1219   }
1220 }
1221
1222 void xbt_os_sem_release(xbt_os_sem_t sem)
1223 {
1224   if (!sem)
1225     THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1226
1227   if (!ReleaseSemaphore(sem->h, 1, NULL))
1228     THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1229            strerror(GetLastError()));
1230   EnterCriticalSection(&(sem->value_lock));
1231   sem->value++;
1232   LeaveCriticalSection(&(sem->value_lock));
1233 }
1234
1235 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1236 {
1237   if (!sem)
1238     THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1239
1240   if (!CloseHandle(sem->h))
1241     THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1242            strerror(GetLastError()));
1243
1244   DeleteCriticalSection(&(sem->value_lock));
1245
1246   xbt_free(sem);
1247
1248 }
1249
1250 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1251 {
1252   if (!sem)
1253     THROWF(arg_error, EINVAL,
1254            "Cannot get the value of the NULL semaphore");
1255
1256   EnterCriticalSection(&(sem->value_lock));
1257   *svalue = sem->value;
1258   LeaveCriticalSection(&(sem->value_lock));
1259 }
1260
1261
1262 #endif
1263
1264
1265 /** @brief Returns the amount of cores on the current host */
1266 int xbt_os_get_numcores(void) {
1267 #ifdef WIN32
1268     SYSTEM_INFO sysinfo;
1269     GetSystemInfo(&sysinfo);
1270     return sysinfo.dwNumberOfProcessors;
1271 #elif defined(__APPLE__) && defined(__MACH__)
1272     int nm[2];
1273     size_t len = 4;
1274     uint32_t count;
1275
1276     nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1277     sysctl(nm, 2, &count, &len, NULL, 0);
1278
1279     if(count < 1) {
1280         nm[1] = HW_NCPU;
1281         sysctl(nm, 2, &count, &len, NULL, 0);
1282         if(count < 1) { count = 1; }
1283     }
1284     return count;
1285 #else
1286     return sysconf(_SC_NPROCESSORS_ONLN);
1287 #endif
1288 }
1289
1290
1291 /***** reentrant mutexes *****/
1292 typedef struct xbt_os_rmutex_ {
1293   xbt_os_mutex_t mutex;
1294   xbt_os_thread_t owner;
1295   int count;
1296 } s_xbt_os_rmutex_t;
1297
1298 void xbt_os_thread_set_extra_data(void *data)
1299 {
1300   xbt_os_thread_self()->extra_data = data;
1301 }
1302
1303 void *xbt_os_thread_get_extra_data(void)
1304 {
1305   xbt_os_thread_t thread = xbt_os_thread_self();
1306   if (thread)
1307     return xbt_os_thread_self()->extra_data;
1308   else
1309     return NULL;
1310 }
1311
1312 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1313 {
1314   xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1315   rmutex->mutex = xbt_os_mutex_init();
1316   rmutex->owner = NULL;
1317   rmutex->count = 0;
1318   return rmutex;
1319 }
1320
1321 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1322 {
1323   xbt_os_thread_t self = xbt_os_thread_self();
1324
1325   if (self == NULL) {
1326     /* the thread module is not initialized yet */
1327     rmutex->owner = NULL;
1328     return;
1329   }
1330
1331   if (self != rmutex->owner) {
1332     xbt_os_mutex_acquire(rmutex->mutex);
1333     rmutex->owner = self;
1334     rmutex->count = 1;
1335   } else {
1336     rmutex->count++;
1337  }
1338 }
1339
1340 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1341 {
1342   if (rmutex->owner == NULL) {
1343     /* the thread module was not initialized */
1344     return;
1345   }
1346
1347   xbt_assert(rmutex->owner == xbt_os_thread_self());
1348
1349   if (--rmutex->count == 0) {
1350     rmutex->owner = NULL;
1351     xbt_os_mutex_release(rmutex->mutex);
1352   }
1353 }
1354
1355 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1356 {
1357   xbt_os_mutex_destroy(rmutex->mutex);
1358   xbt_free(rmutex);
1359 }