Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
set a SimGrid identity to maestro on windows too
[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            "Impossible to set the SimGrid identity descriptor to the main thread (pthread_setspecific failed)");
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   main_thread = xbt_new(s_xbt_os_thread_t, 1);
734   main_thread->name = (char *) "main";
735   main_thread->start_routine = NULL;
736   main_thread->param = NULL;
737   main_thread->running_ctx = xbt_new(xbt_running_ctx_t, 1);
738   XBT_RUNNING_CTX_INITIALIZE(main_thread->running_ctx);
739
740   if (!TlsSetValue(xbt_self_thread_key, main_thread))
741     THROWF(system_error, errcode,
742            "Impossible to set the SimGrid identity descriptor to the main thread (TlsSetValue() failed)");
743
744 }
745
746 void xbt_os_thread_mod_postexit(void)
747 {
748
749   if (!TlsFree(xbt_self_thread_key))
750     THROWF(system_error, (int) GetLastError(),
751            "TlsFree() failed to cleanup the thread submodule");
752 }
753
754 int xbt_os_thread_atfork(void (*prepare)(void),
755                          void (*parent)(void), void (*child)(void))
756 {
757   return 0;
758 }
759
760 static DWORD WINAPI wrapper_start_routine(void *s)
761 {
762   xbt_os_thread_t t = (xbt_os_thread_t) s;
763   DWORD *rv;
764
765   if (!TlsSetValue(xbt_self_thread_key, t))
766     THROWF(system_error, (int) GetLastError(),
767            "TlsSetValue of data describing the created thread failed");
768
769   rv = (DWORD *) ((t->start_routine) (t->param));
770
771   return rv ? *rv : 0;
772
773 }
774
775
776 xbt_os_thread_t xbt_os_thread_create(const char *name,
777                                      pvoid_f_pvoid_t start_routine,
778                                      void *param,
779                                      void *extra_data)
780 {
781
782   xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
783
784   t->name = xbt_strdup(name);
785   t->start_routine = start_routine;
786   t->param = param;
787   t->extra_data = extra_data;
788   t->handle = CreateThread(NULL, stack_size==0 ? XBT_DEFAULT_THREAD_STACK_SIZE : stack_size,
789                            (LPTHREAD_START_ROUTINE) wrapper_start_routine,
790                            t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
791
792   if (!t->handle) {
793     xbt_free(t);
794     THROWF(system_error, (int) GetLastError(), "CreateThread failed");
795   }
796
797   return t;
798 }
799
800 void xbt_os_thread_setstacksize(int size)
801 {
802   stack_size = size;
803 }
804
805 void xbt_os_thread_setguardsize(int size)
806 {
807   XBT_WARN("xbt_os_thread_setguardsize is not implemented (%d)", size);
808 }
809
810 const char *xbt_os_thread_name(xbt_os_thread_t t)
811 {
812   return t->name;
813 }
814
815 const char *xbt_os_thread_self_name(void)
816 {
817   xbt_os_thread_t t = xbt_os_thread_self();
818   return t ? t->name : "main";
819 }
820
821 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
822 {
823
824   if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
825     THROWF(system_error, (int) GetLastError(),
826            "WaitForSingleObject failed");
827
828   if (thread_return) {
829
830     if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
831       THROWF(system_error, (int) GetLastError(),
832              "GetExitCodeThread failed");
833   }
834
835   CloseHandle(thread->handle);
836
837   free(thread->name);
838
839   free(thread);
840 }
841
842 void xbt_os_thread_exit(int *retval)
843 {
844   if (retval)
845     ExitThread(*retval);
846   else
847     ExitThread(0);
848 }
849
850 void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
851
852   *key = TlsAlloc();
853 }
854
855 void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
856
857   if (!TlsSetValue(key, value))
858     THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
859 }
860
861 void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
862   return TlsGetValue(key);
863 }
864
865 void xbt_os_thread_detach(xbt_os_thread_t thread)
866 {
867   THROW_UNIMPLEMENTED;
868 }
869
870
871 xbt_os_thread_t xbt_os_thread_self(void)
872 {
873   return TlsGetValue(xbt_self_thread_key);
874 }
875
876 void *xbt_os_thread_getparam(void)
877 {
878   xbt_os_thread_t t = xbt_os_thread_self();
879   return t->param;
880 }
881
882
883 void xbt_os_thread_yield(void)
884 {
885   Sleep(0);
886 }
887
888 void xbt_os_thread_cancel(xbt_os_thread_t t)
889 {
890   if (!TerminateThread(t->handle, 0))
891     THROWF(system_error, (int) GetLastError(), "TerminateThread failed");
892 }
893
894 /****** mutex related functions ******/
895 typedef struct xbt_os_mutex_ {
896   /* KEEP IT IN SYNC WITH xbt_thread.c */
897   CRITICAL_SECTION lock;
898 } s_xbt_os_mutex_t;
899
900 xbt_os_mutex_t xbt_os_mutex_init(void)
901 {
902   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
903
904   /* initialize the critical section object */
905   InitializeCriticalSection(&(res->lock));
906
907   return res;
908 }
909
910 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
911 {
912   EnterCriticalSection(&mutex->lock);
913 }
914
915 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
916 {
917   THROW_UNIMPLEMENTED;
918 }
919
920 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
921 {
922
923   LeaveCriticalSection(&mutex->lock);
924
925 }
926
927 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
928 {
929
930   if (!mutex)
931     return;
932
933   DeleteCriticalSection(&mutex->lock);
934   free(mutex);
935 }
936
937 /***** condition related functions *****/
938 enum {                          /* KEEP IT IN SYNC WITH xbt_thread.c */
939   SIGNAL = 0,
940   BROADCAST = 1,
941   MAX_EVENTS = 2
942 };
943
944 typedef struct xbt_os_cond_ {
945   /* KEEP IT IN SYNC WITH xbt_thread.c */
946   HANDLE events[MAX_EVENTS];
947
948   unsigned int waiters_count;   /* the number of waiters                        */
949   CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
950 } s_xbt_os_cond_t;
951
952 xbt_os_cond_t xbt_os_cond_init(void)
953 {
954
955   xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
956
957   memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
958
959   /* initialize the critical section object */
960   InitializeCriticalSection(&res->waiters_count_lock);
961
962   res->waiters_count = 0;
963
964   /* Create an auto-reset event */
965   res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
966
967   if (!res->events[SIGNAL]) {
968     DeleteCriticalSection(&res->waiters_count_lock);
969     free(res);
970     THROWF(system_error, 0, "CreateEvent failed for the signals");
971   }
972
973   /* Create a manual-reset event. */
974   res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
975
976   if (!res->events[BROADCAST]) {
977
978     DeleteCriticalSection(&res->waiters_count_lock);
979     CloseHandle(res->events[SIGNAL]);
980     free(res);
981     THROWF(system_error, 0, "CreateEvent failed for the broadcasts");
982   }
983
984   return res;
985 }
986
987 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
988 {
989
990   unsigned long wait_result;
991   int is_last_waiter;
992
993   /* lock the threads counter and increment it */
994   EnterCriticalSection(&cond->waiters_count_lock);
995   cond->waiters_count++;
996   LeaveCriticalSection(&cond->waiters_count_lock);
997
998   /* unlock the mutex associate with the condition */
999   LeaveCriticalSection(&mutex->lock);
1000
1001   /* wait for a signal (broadcast or no) */
1002   wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
1003
1004   if (wait_result == WAIT_FAILED)
1005     THROWF(system_error, 0,
1006            "WaitForMultipleObjects failed, so we cannot wait on the condition");
1007
1008   /* we have a signal lock the condition */
1009   EnterCriticalSection(&cond->waiters_count_lock);
1010   cond->waiters_count--;
1011
1012   /* it's the last waiter or it's a broadcast ? */
1013   is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1014                     && (cond->waiters_count == 0));
1015
1016   LeaveCriticalSection(&cond->waiters_count_lock);
1017
1018   /* yes it's the last waiter or it's a broadcast
1019    * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1020    * by the system.
1021    */
1022   if (is_last_waiter)
1023     if (!ResetEvent(cond->events[BROADCAST]))
1024       THROWF(system_error, 0, "ResetEvent failed");
1025
1026   /* relock the mutex associated with the condition in accordance with the posix thread specification */
1027   EnterCriticalSection(&mutex->lock);
1028 }
1029
1030 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
1031                            double delay)
1032 {
1033
1034   unsigned long wait_result = WAIT_TIMEOUT;
1035   int is_last_waiter;
1036   unsigned long end = (unsigned long) (delay * 1000);
1037
1038
1039   if (delay < 0) {
1040     xbt_os_cond_wait(cond, mutex);
1041   } else {
1042     XBT_DEBUG("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events),
1043            &(mutex->lock), end);
1044
1045     /* lock the threads counter and increment it */
1046     EnterCriticalSection(&cond->waiters_count_lock);
1047     cond->waiters_count++;
1048     LeaveCriticalSection(&cond->waiters_count_lock);
1049
1050     /* unlock the mutex associate with the condition */
1051     LeaveCriticalSection(&mutex->lock);
1052     /* wait for a signal (broadcast or no) */
1053
1054     wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
1055
1056     switch (wait_result) {
1057     case WAIT_TIMEOUT:
1058       THROWF(timeout_error, GetLastError(),
1059              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
1060              cond, mutex, delay);
1061     case WAIT_FAILED:
1062       THROWF(system_error, GetLastError(),
1063              "WaitForMultipleObjects failed, so we cannot wait on the condition");
1064     }
1065
1066     /* we have a signal lock the condition */
1067     EnterCriticalSection(&cond->waiters_count_lock);
1068     cond->waiters_count--;
1069
1070     /* it's the last waiter or it's a broadcast ? */
1071     is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
1072                       && (cond->waiters_count == 0));
1073
1074     LeaveCriticalSection(&cond->waiters_count_lock);
1075
1076     /* yes it's the last waiter or it's a broadcast
1077      * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
1078      * by the system.
1079      */
1080     if (is_last_waiter)
1081       if (!ResetEvent(cond->events[BROADCAST]))
1082         THROWF(system_error, 0, "ResetEvent failed");
1083
1084     /* relock the mutex associated with the condition in accordance with the posix thread specification */
1085     EnterCriticalSection(&mutex->lock);
1086   }
1087   /*THROW_UNIMPLEMENTED; */
1088 }
1089
1090 void xbt_os_cond_signal(xbt_os_cond_t cond)
1091 {
1092   int have_waiters;
1093
1094   EnterCriticalSection(&cond->waiters_count_lock);
1095   have_waiters = cond->waiters_count > 0;
1096   LeaveCriticalSection(&cond->waiters_count_lock);
1097
1098   if (have_waiters)
1099     if (!SetEvent(cond->events[SIGNAL]))
1100       THROWF(system_error, 0, "SetEvent failed");
1101
1102   xbt_os_thread_yield();
1103 }
1104
1105 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
1106 {
1107   int have_waiters;
1108
1109   EnterCriticalSection(&cond->waiters_count_lock);
1110   have_waiters = cond->waiters_count > 0;
1111   LeaveCriticalSection(&cond->waiters_count_lock);
1112
1113   if (have_waiters)
1114     SetEvent(cond->events[BROADCAST]);
1115 }
1116
1117 void xbt_os_cond_destroy(xbt_os_cond_t cond)
1118 {
1119   int error = 0;
1120
1121   if (!cond)
1122     return;
1123
1124   if (!CloseHandle(cond->events[SIGNAL]))
1125     error = 1;
1126
1127   if (!CloseHandle(cond->events[BROADCAST]))
1128     error = 1;
1129
1130   DeleteCriticalSection(&cond->waiters_count_lock);
1131
1132   xbt_free(cond);
1133
1134   if (error)
1135     THROWF(system_error, 0, "Error while destroying the condition");
1136 }
1137
1138 typedef struct xbt_os_sem_ {
1139   HANDLE h;
1140   unsigned int value;
1141   CRITICAL_SECTION value_lock;  /* protect access to value of the semaphore  */
1142 } s_xbt_os_sem_t;
1143
1144 #ifndef INT_MAX
1145 # define INT_MAX 32767          /* let's be safe by underestimating this value: this is for 16bits only */
1146 #endif
1147
1148 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
1149 {
1150   xbt_os_sem_t res;
1151
1152   if (value > INT_MAX)
1153     THROWF(arg_error, value,
1154            "Semaphore initial value too big: %ud cannot be stored as a signed int",
1155            value);
1156
1157   res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
1158
1159   if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
1160     THROWF(system_error, GetLastError(), "CreateSemaphore() failed: %s",
1161            strerror(GetLastError()));
1162     return NULL;
1163   }
1164
1165   res->value = value;
1166
1167   InitializeCriticalSection(&(res->value_lock));
1168
1169   return res;
1170 }
1171
1172 void xbt_os_sem_acquire(xbt_os_sem_t sem)
1173 {
1174   if (!sem)
1175     THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1176
1177   /* wait failure */
1178   if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1179     THROWF(system_error, GetLastError(),
1180            "WaitForSingleObject() failed: %s", strerror(GetLastError()));
1181   EnterCriticalSection(&(sem->value_lock));
1182   sem->value--;
1183   LeaveCriticalSection(&(sem->value_lock));
1184 }
1185
1186 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1187 {
1188   long seconds;
1189   long milliseconds;
1190   double end = timeout + xbt_os_time();
1191
1192   if (!sem)
1193     THROWF(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1194
1195   if (timeout < 0) {
1196     xbt_os_sem_acquire(sem);
1197   } else {                      /* timeout can be zero <-> try acquire ) */
1198
1199
1200     seconds = (long) floor(end);
1201     milliseconds = (long) ((end - seconds) * 1000);
1202     milliseconds += (seconds * 1000);
1203
1204     switch (WaitForSingleObject(sem->h, milliseconds)) {
1205     case WAIT_OBJECT_0:
1206       EnterCriticalSection(&(sem->value_lock));
1207       sem->value--;
1208       LeaveCriticalSection(&(sem->value_lock));
1209       return;
1210
1211     case WAIT_TIMEOUT:
1212       THROWF(timeout_error, GetLastError(),
1213              "semaphore %p wasn't signaled before timeout (%f)", sem,
1214              timeout);
1215       return;
1216
1217     default:
1218       THROWF(system_error, GetLastError(),
1219              "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1220              strerror(GetLastError()));
1221     }
1222   }
1223 }
1224
1225 void xbt_os_sem_release(xbt_os_sem_t sem)
1226 {
1227   if (!sem)
1228     THROWF(arg_error, EINVAL, "Cannot release the NULL semaphore");
1229
1230   if (!ReleaseSemaphore(sem->h, 1, NULL))
1231     THROWF(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1232            strerror(GetLastError()));
1233   EnterCriticalSection(&(sem->value_lock));
1234   sem->value++;
1235   LeaveCriticalSection(&(sem->value_lock));
1236 }
1237
1238 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1239 {
1240   if (!sem)
1241     THROWF(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1242
1243   if (!CloseHandle(sem->h))
1244     THROWF(system_error, GetLastError(), "CloseHandle() failed: %s",
1245            strerror(GetLastError()));
1246
1247   DeleteCriticalSection(&(sem->value_lock));
1248
1249   xbt_free(sem);
1250
1251 }
1252
1253 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1254 {
1255   if (!sem)
1256     THROWF(arg_error, EINVAL,
1257            "Cannot get the value of the NULL semaphore");
1258
1259   EnterCriticalSection(&(sem->value_lock));
1260   *svalue = sem->value;
1261   LeaveCriticalSection(&(sem->value_lock));
1262 }
1263
1264
1265 #endif
1266
1267
1268 /** @brief Returns the amount of cores on the current host */
1269 int xbt_os_get_numcores(void) {
1270 #ifdef WIN32
1271     SYSTEM_INFO sysinfo;
1272     GetSystemInfo(&sysinfo);
1273     return sysinfo.dwNumberOfProcessors;
1274 #elif defined(__APPLE__) && defined(__MACH__)
1275     int nm[2];
1276     size_t len = 4;
1277     uint32_t count;
1278
1279     nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
1280     sysctl(nm, 2, &count, &len, NULL, 0);
1281
1282     if(count < 1) {
1283         nm[1] = HW_NCPU;
1284         sysctl(nm, 2, &count, &len, NULL, 0);
1285         if(count < 1) { count = 1; }
1286     }
1287     return count;
1288 #else
1289     return sysconf(_SC_NPROCESSORS_ONLN);
1290 #endif
1291 }
1292
1293
1294 /***** reentrant mutexes *****/
1295 typedef struct xbt_os_rmutex_ {
1296   xbt_os_mutex_t mutex;
1297   xbt_os_thread_t owner;
1298   int count;
1299 } s_xbt_os_rmutex_t;
1300
1301 void xbt_os_thread_set_extra_data(void *data)
1302 {
1303   xbt_os_thread_self()->extra_data = data;
1304 }
1305
1306 void *xbt_os_thread_get_extra_data(void)
1307 {
1308   xbt_os_thread_t self = xbt_os_thread_self();
1309   return self? self->extra_data : NULL;
1310 }
1311
1312 xbt_os_rmutex_t xbt_os_rmutex_init(void)
1313 {
1314   xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 1);
1315   rmutex->mutex = xbt_os_mutex_init();
1316   rmutex->owner = NULL;
1317   rmutex->count = 0;
1318   return rmutex;
1319 }
1320
1321 void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
1322 {
1323   xbt_os_thread_t self = xbt_os_thread_self();
1324
1325   if (self == NULL) {
1326     /* the thread module is not initialized yet */
1327     rmutex->owner = NULL;
1328     return;
1329   }
1330
1331   if (self != rmutex->owner) {
1332     xbt_os_mutex_acquire(rmutex->mutex);
1333     rmutex->owner = self;
1334     rmutex->count = 1;
1335   } else {
1336     rmutex->count++;
1337  }
1338 }
1339
1340 void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
1341 {
1342   if (rmutex->owner == NULL) {
1343     /* the thread module was not initialized */
1344     return;
1345   }
1346
1347   xbt_assert(rmutex->owner == xbt_os_thread_self());
1348
1349   if (--rmutex->count == 0) {
1350     rmutex->owner = NULL;
1351     xbt_os_mutex_release(rmutex->mutex);
1352   }
1353 }
1354
1355 void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
1356 {
1357   xbt_os_mutex_destroy(rmutex->mutex);
1358   xbt_free(rmutex);
1359 }