Logo AND Algorithmique Numérique Distribuée

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