Logo AND Algorithmique Numérique Distribuée

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