Logo AND Algorithmique Numérique Distribuée

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