Logo AND Algorithmique Numérique Distribuée

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