Logo AND Algorithmique Numérique Distribuée

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