Logo AND Algorithmique Numérique Distribuée

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