Logo AND Algorithmique Numérique Distribuée

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