Logo AND Algorithmique Numérique Distribuée

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