Logo AND Algorithmique Numérique Distribuée

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