Logo AND Algorithmique Numérique Distribuée

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