Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
change mmalloc.h into a public header
[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_init(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_exit(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 self = xbt_os_thread_self();
166   return self ? self->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, "xbt_mutex_timedacquire(%p) failed: %s",
267              mutex, strerror(errcode));
268     }
269
270
271   } else {
272
273 #ifdef HAVE_MUTEX_TIMEDLOCK
274     struct timespec ts_end;
275     double end = delay + xbt_os_time();
276
277     ts_end.tv_sec = (time_t) floor(end);
278     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
279     DEBUG2("pthread_mutex_timedlock(%p,%p)", &(mutex->m), &ts_end);
280
281     errcode = pthread_mutex_timedlock(&(mutex->m), &ts_end);
282
283 #else /* Well, let's reimplement it since those lazy libc dudes didn't */
284     double start = xbt_os_time();
285     do {
286       errcode = pthread_mutex_trylock(&(mutex->m));
287       if (errcode == EBUSY)
288         xbt_os_thread_yield();
289     } while (errcode == EBUSY && xbt_os_time() - start < delay);
290
291     if (errcode == EBUSY)
292       errcode = ETIMEDOUT;
293
294 #endif /* HAVE_MUTEX_TIMEDLOCK */
295
296     switch (errcode) {
297     case 0:
298       return;
299
300     case ETIMEDOUT:
301       THROW2(timeout_error, delay,
302              "mutex %p wasn't signaled before timeout (%f)", mutex, delay);
303
304     default:
305       THROW3(system_error, errcode,
306              "pthread_mutex_timedlock(%p,%f) failed: %s", mutex, delay,
307              strerror(errcode));
308     }
309   }
310 }
311
312 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
313 {
314   int errcode;
315
316   if ((errcode = pthread_mutex_unlock(&(mutex->m))))
317     THROW2(system_error, errcode, "pthread_mutex_unlock(%p) failed: %s",
318            mutex, strerror(errcode));
319 }
320
321 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
322 {
323   int errcode;
324
325   if (!mutex)
326     return;
327
328   if ((errcode = pthread_mutex_destroy(&(mutex->m))))
329     THROW2(system_error, errcode, "pthread_mutex_destroy(%p) failed: %s",
330            mutex, strerror(errcode));
331   free(mutex);
332 }
333
334 /***** condition related functions *****/
335 typedef struct xbt_os_cond_ {
336   /* KEEP IT IN SYNC WITH xbt_thread.c */
337   pthread_cond_t c;
338 } s_xbt_os_cond_t;
339
340 xbt_os_cond_t xbt_os_cond_init(void)
341 {
342   xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t, 1);
343   int errcode;
344   if ((errcode = pthread_cond_init(&(res->c), NULL)))
345     THROW1(system_error, errcode, "pthread_cond_init() failed: %s",
346            strerror(errcode));
347
348   return res;
349 }
350
351 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
352 {
353   int errcode;
354   if ((errcode = pthread_cond_wait(&(cond->c), &(mutex->m))))
355     THROW3(system_error, errcode, "pthread_cond_wait(%p,%p) failed: %s",
356            cond, mutex, strerror(errcode));
357 }
358
359
360 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
361                            double delay)
362 {
363   int errcode;
364   struct timespec ts_end;
365   double end = delay + xbt_os_time();
366
367   if (delay < 0) {
368     xbt_os_cond_wait(cond, mutex);
369   } else {
370     ts_end.tv_sec = (time_t) floor(end);
371     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
372     DEBUG3("pthread_cond_timedwait(%p,%p,%p)", &(cond->c), &(mutex->m),
373            &ts_end);
374     switch ((errcode =
375              pthread_cond_timedwait(&(cond->c), &(mutex->m), &ts_end))) {
376     case 0:
377       return;
378     case ETIMEDOUT:
379       THROW3(timeout_error, errcode,
380              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
381              cond, mutex, delay);
382     default:
383       THROW4(system_error, errcode,
384              "pthread_cond_timedwait(%p,%p,%f) failed: %s", cond, mutex,
385              delay, strerror(errcode));
386     }
387   }
388 }
389
390 void xbt_os_cond_signal(xbt_os_cond_t cond)
391 {
392   int errcode;
393   if ((errcode = pthread_cond_signal(&(cond->c))))
394     THROW2(system_error, errcode, "pthread_cond_signal(%p) failed: %s",
395            cond, strerror(errcode));
396 }
397
398 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
399 {
400   int errcode;
401   if ((errcode = pthread_cond_broadcast(&(cond->c))))
402     THROW2(system_error, errcode, "pthread_cond_broadcast(%p) failed: %s",
403            cond, strerror(errcode));
404 }
405
406 void xbt_os_cond_destroy(xbt_os_cond_t cond)
407 {
408   int errcode;
409
410   if (!cond)
411     return;
412
413   if ((errcode = pthread_cond_destroy(&(cond->c))))
414     THROW2(system_error, errcode, "pthread_cond_destroy(%p) failed: %s",
415            cond, strerror(errcode));
416   free(cond);
417 }
418
419 void *xbt_os_thread_getparam(void)
420 {
421   xbt_os_thread_t t = xbt_os_thread_self();
422   return t ? t->param : NULL;
423 }
424
425 typedef struct xbt_os_sem_ {
426 #ifndef HAVE_SEM_INIT
427   char *name;
428 #endif
429   sem_t s;
430   sem_t *ps;
431 } s_xbt_os_sem_t;
432
433 #ifndef SEM_FAILED
434 #define SEM_FAILED (-1)
435 #endif
436
437 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
438 {
439   xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t, 1);
440
441   /* On some systems (MAC OS X), only the stub of sem_init is to be found.
442    * Any attempt to use it leads to ENOSYS (function not implemented).
443    * If such a prehistoric system is detected, do the job with sem_open instead
444    */
445 #ifdef HAVE_SEM_INIT
446   if (sem_init(&(res->s), 0, value) != 0)
447     THROW1(system_error, errno, "sem_init() failed: %s", strerror(errno));
448   res->ps = &(res->s);
449
450 #else /* damn, no sem_init(). Reimplement it */
451
452   xbt_os_mutex_acquire(next_sem_ID_lock);
453   res->name = bprintf("/%d.%d", (*xbt_getpid) (), ++next_sem_ID);
454   xbt_os_mutex_release(next_sem_ID_lock);
455
456   res->ps = sem_open(res->name, O_CREAT, 0644, value);
457   if ((res->ps == (sem_t *) SEM_FAILED) && (errno == ENAMETOOLONG)) {
458     /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */
459     res->name[13] = '\0';
460     res->ps = sem_open(res->name, O_CREAT, 0644, 1);
461   }
462   if ((res->ps == (sem_t *) SEM_FAILED))
463     THROW1(system_error, errno, "sem_open() failed: %s", strerror(errno));
464
465   /* Remove the name from the semaphore namespace: we never join on it */
466   if (sem_unlink(res->name) < 0)
467     THROW1(system_error, errno, "sem_unlink() failed: %s", strerror(errno));
468
469 #endif
470
471   return res;
472 }
473
474 void xbt_os_sem_acquire(xbt_os_sem_t sem)
475 {
476   if (!sem)
477     THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
478   if (sem_wait(sem->ps) < 0)
479     THROW1(system_error, errno, "sem_wait() failed: %s", strerror(errno));
480 }
481
482 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay)
483 {
484   int errcode;
485
486   if (!sem)
487     THROW0(arg_error, EINVAL, "Cannot acquire of the NULL semaphore");
488
489   if (delay < 0) {
490     xbt_os_sem_acquire(sem);
491   } else if (delay == 0) {
492     errcode = sem_trywait(sem->ps);
493
494     switch (errcode) {
495     case 0:
496       return;
497     case ETIMEDOUT:
498       THROW1(timeout_error, 0, "semaphore %p not ready", sem);
499     default:
500       THROW2(system_error, errcode, "xbt_os_sem_timedacquire(%p) failed: %s",
501              sem, strerror(errcode));
502     }
503
504   } else {
505 #ifdef HAVE_SEM_WAIT
506     struct timespec ts_end;
507     double end = delay + xbt_os_time();
508
509     ts_end.tv_sec = (time_t) floor(end);
510     ts_end.tv_nsec = (long) ((end - ts_end.tv_sec) * 1000000000);
511     DEBUG2("sem_timedwait(%p,%p)", sem->ps, &ts_end);
512     errcode = sem_timedwait(sem->s, &ts_end);
513
514 #else /* Okay, reimplement this function then */
515     double start = xbt_os_time();
516     do {
517       errcode = sem_trywait(sem->ps);
518       if (errcode == EBUSY)
519         xbt_os_thread_yield();
520     } while (errcode == EBUSY && xbt_os_time() - start < delay);
521
522     if (errcode == EBUSY)
523       errcode = ETIMEDOUT;
524 #endif
525
526     switch (errcode) {
527     case 0:
528       return;
529
530     case ETIMEDOUT:
531       THROW2(timeout_error, delay,
532              "semaphore %p wasn't signaled before timeout (%f)", sem, delay);
533
534     default:
535       THROW3(system_error, errcode, "sem_timedwait(%p,%f) failed: %s", sem,
536              delay, strerror(errcode));
537     }
538   }
539 }
540
541 void xbt_os_sem_release(xbt_os_sem_t sem)
542 {
543   if (!sem)
544     THROW0(arg_error, EINVAL, "Cannot release of the NULL semaphore");
545
546   if (sem_post(sem->ps) < 0)
547     THROW1(system_error, errno, "sem_post() failed: %s", strerror(errno));
548 }
549
550 void xbt_os_sem_destroy(xbt_os_sem_t sem)
551 {
552   if (!sem)
553     THROW0(arg_error, EINVAL, "Cannot destroy the NULL sempahore");
554
555 #ifdef HAVE_SEM_INIT
556   if (sem_destroy(sem->ps))
557     <0)
558       THROW1(system_error, errno, "sem_destroy() failed: %s",
559              strerror(errno));
560 #else
561   if (sem_close(sem->ps) < 0)
562     THROW1(system_error, errno, "sem_close() failed: %s", strerror(errno));
563   xbt_free(sem->name);
564
565 #endif
566   xbt_free(sem);
567 }
568
569 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
570 {
571   if (!sem)
572     THROW0(arg_error, EINVAL, "Cannot get the value of the NULL semaphore");
573
574   if (sem_getvalue(&(sem->s), svalue) < 0)
575     THROW1(system_error, errno, "sem_getvalue() failed: %s", strerror(errno));
576 }
577
578 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
579
580 #elif defined(WIN32)
581
582 #include <math.h>
583
584 typedef struct xbt_os_thread_ {
585   char *name;
586   HANDLE handle;                /* the win thread handle        */
587   unsigned long id;             /* the win thread id            */
588   pvoid_f_pvoid_t start_routine;
589   void *param;
590 } s_xbt_os_thread_t;
591
592 /* so we can specify the size of the stack of the threads */
593 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
594 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
595 #endif
596
597 /* the default size of the stack of the threads (in bytes)*/
598 #define XBT_DEFAULT_THREAD_STACK_SIZE   4096
599
600 /* key to the TLS containing the xbt_os_thread_t structure */
601 static unsigned long xbt_self_thread_key;
602
603 void xbt_os_thread_mod_init(void)
604 {
605   xbt_self_thread_key = TlsAlloc();
606 }
607
608 void xbt_os_thread_mod_exit(void)
609 {
610
611   if (!TlsFree(xbt_self_thread_key))
612     THROW0(system_error, (int) GetLastError(),
613            "TlsFree() failed to cleanup the thread submodule");
614 }
615
616 static DWORD WINAPI wrapper_start_routine(void *s)
617 {
618   xbt_os_thread_t t = (xbt_os_thread_t) s;
619   DWORD *rv;
620
621   if (!TlsSetValue(xbt_self_thread_key, t))
622     THROW0(system_error, (int) GetLastError(),
623            "TlsSetValue of data describing the created thread failed");
624
625   rv = (DWORD *) ((t->start_routine) (t->param));
626
627   return rv ? *rv : 0;
628
629 }
630
631
632 xbt_os_thread_t xbt_os_thread_create(const char *name,
633                                      pvoid_f_pvoid_t start_routine,
634                                      void *param)
635 {
636
637   xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t, 1);
638
639   t->name = xbt_strdup(name);
640   t->start_routine = start_routine;
641   t->param = param;
642
643   t->handle = CreateThread(NULL, XBT_DEFAULT_THREAD_STACK_SIZE,
644                            (LPTHREAD_START_ROUTINE) wrapper_start_routine,
645                            t, STACK_SIZE_PARAM_IS_A_RESERVATION, &(t->id));
646
647   if (!t->handle) {
648     xbt_free(t);
649     THROW0(system_error, (int) GetLastError(), "CreateThread failed");
650   }
651
652   return t;
653 }
654
655 const char *xbt_os_thread_name(xbt_os_thread_t t)
656 {
657   return t->name;
658 }
659
660 const char *xbt_os_thread_self_name(void)
661 {
662   xbt_os_thread_t t = xbt_os_thread_self();
663   return t ? t->name : "main";
664 }
665
666 void xbt_os_thread_join(xbt_os_thread_t thread, void **thread_return)
667 {
668
669   if (WAIT_OBJECT_0 != WaitForSingleObject(thread->handle, INFINITE))
670     THROW0(system_error, (int) GetLastError(), "WaitForSingleObject failed");
671
672   if (thread_return) {
673
674     if (!GetExitCodeThread(thread->handle, (DWORD *) (*thread_return)))
675       THROW0(system_error, (int) GetLastError(), "GetExitCodeThread failed");
676   }
677
678   CloseHandle(thread->handle);
679
680   if (thread->name)
681     free(thread->name);
682
683   free(thread);
684 }
685
686 void xbt_os_thread_exit(int *retval)
687 {
688   if (retval)
689     ExitThread(*retval);
690   else
691     ExitThread(0);
692 }
693
694 xbt_os_thread_t xbt_os_thread_self(void)
695 {
696   return TlsGetValue(xbt_self_thread_key);
697 }
698
699 void *xbt_os_thread_getparam(void)
700 {
701   xbt_os_thread_t t = xbt_os_thread_self();
702   return t->param;
703 }
704
705
706 void xbt_os_thread_yield(void)
707 {
708   Sleep(0);
709 }
710
711 void xbt_os_thread_cancel(xbt_os_thread_t t)
712 {
713   if (!TerminateThread(t->handle, 0))
714     THROW0(system_error, (int) GetLastError(), "TerminateThread failed");
715 }
716
717 /****** mutex related functions ******/
718 typedef struct xbt_os_mutex_ {
719   /* KEEP IT IN SYNC WITH xbt_thread.c */
720   CRITICAL_SECTION lock;
721 } s_xbt_os_mutex_t;
722
723 xbt_os_mutex_t xbt_os_mutex_init(void)
724 {
725   xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
726
727   /* initialize the critical section object */
728   InitializeCriticalSection(&(res->lock));
729
730   return res;
731 }
732
733 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
734 {
735   EnterCriticalSection(&mutex->lock);
736 }
737
738 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay)
739 {
740   THROW_UNIMPLEMENTED;
741 }
742
743 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
744 {
745
746   LeaveCriticalSection(&mutex->lock);
747
748 }
749
750 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
751 {
752
753   if (!mutex)
754     return;
755
756   DeleteCriticalSection(&mutex->lock);
757   free(mutex);
758 }
759
760 /***** condition related functions *****/
761 enum {                          /* KEEP IT IN SYNC WITH xbt_thread.c */
762   SIGNAL = 0,
763   BROADCAST = 1,
764   MAX_EVENTS = 2
765 };
766
767 typedef struct xbt_os_cond_ {
768   /* KEEP IT IN SYNC WITH xbt_thread.c */
769   HANDLE events[MAX_EVENTS];
770
771   unsigned int waiters_count;   /* the number of waiters                        */
772   CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
773 } s_xbt_os_cond_t;
774
775 xbt_os_cond_t xbt_os_cond_init(void)
776 {
777
778   xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t, 1);
779
780   memset(&res->waiters_count_lock, 0, sizeof(CRITICAL_SECTION));
781
782   /* initialize the critical section object */
783   InitializeCriticalSection(&res->waiters_count_lock);
784
785   res->waiters_count = 0;
786
787   /* Create an auto-reset event */
788   res->events[SIGNAL] = CreateEvent(NULL, FALSE, FALSE, NULL);
789
790   if (!res->events[SIGNAL]) {
791     DeleteCriticalSection(&res->waiters_count_lock);
792     free(res);
793     THROW0(system_error, 0, "CreateEvent failed for the signals");
794   }
795
796   /* Create a manual-reset event. */
797   res->events[BROADCAST] = CreateEvent(NULL, TRUE, FALSE, NULL);
798
799   if (!res->events[BROADCAST]) {
800
801     DeleteCriticalSection(&res->waiters_count_lock);
802     CloseHandle(res->events[SIGNAL]);
803     free(res);
804     THROW0(system_error, 0, "CreateEvent failed for the broadcasts");
805   }
806
807   return res;
808 }
809
810 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex)
811 {
812
813   unsigned long wait_result;
814   int is_last_waiter;
815
816   /* lock the threads counter and increment it */
817   EnterCriticalSection(&cond->waiters_count_lock);
818   cond->waiters_count++;
819   LeaveCriticalSection(&cond->waiters_count_lock);
820
821   /* unlock the mutex associate with the condition */
822   LeaveCriticalSection(&mutex->lock);
823
824   /* wait for a signal (broadcast or no) */
825   wait_result = WaitForMultipleObjects(2, cond->events, FALSE, INFINITE);
826
827   if (wait_result == WAIT_FAILED)
828     THROW0(system_error, 0,
829            "WaitForMultipleObjects failed, so we cannot wait on the condition");
830
831   /* we have a signal lock the condition */
832   EnterCriticalSection(&cond->waiters_count_lock);
833   cond->waiters_count--;
834
835   /* it's the last waiter or it's a broadcast ? */
836   is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
837                     && (cond->waiters_count == 0));
838
839   LeaveCriticalSection(&cond->waiters_count_lock);
840
841   /* yes it's the last waiter or it's a broadcast
842    * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
843    * by the system.
844    */
845   if (is_last_waiter)
846     if (!ResetEvent(cond->events[BROADCAST]))
847       THROW0(system_error, 0, "ResetEvent failed");
848
849   /* relock the mutex associated with the condition in accordance with the posix thread specification */
850   EnterCriticalSection(&mutex->lock);
851 }
852
853 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex,
854                            double delay)
855 {
856
857   unsigned long wait_result = WAIT_TIMEOUT;
858   int is_last_waiter;
859   unsigned long end = (unsigned long) (delay * 1000);
860
861
862   if (delay < 0) {
863     xbt_os_cond_wait(cond, mutex);
864   } else {
865     DEBUG3("xbt_cond_timedwait(%p,%p,%lu)", &(cond->events), &(mutex->lock),
866            end);
867
868     /* lock the threads counter and increment it */
869     EnterCriticalSection(&cond->waiters_count_lock);
870     cond->waiters_count++;
871     LeaveCriticalSection(&cond->waiters_count_lock);
872
873     /* unlock the mutex associate with the condition */
874     LeaveCriticalSection(&mutex->lock);
875     /* wait for a signal (broadcast or no) */
876
877     wait_result = WaitForMultipleObjects(2, cond->events, FALSE, end);
878
879     switch (wait_result) {
880     case WAIT_TIMEOUT:
881       THROW3(timeout_error, GetLastError(),
882              "condition %p (mutex %p) wasn't signaled before timeout (%f)",
883              cond, mutex, delay);
884     case WAIT_FAILED:
885       THROW0(system_error, GetLastError(),
886              "WaitForMultipleObjects failed, so we cannot wait on the condition");
887     }
888
889     /* we have a signal lock the condition */
890     EnterCriticalSection(&cond->waiters_count_lock);
891     cond->waiters_count--;
892
893     /* it's the last waiter or it's a broadcast ? */
894     is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1)
895                       && (cond->waiters_count == 0));
896
897     LeaveCriticalSection(&cond->waiters_count_lock);
898
899     /* yes it's the last waiter or it's a broadcast
900      * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
901      * by the system.
902      */
903     if (is_last_waiter)
904       if (!ResetEvent(cond->events[BROADCAST]))
905         THROW0(system_error, 0, "ResetEvent failed");
906
907     /* relock the mutex associated with the condition in accordance with the posix thread specification */
908     EnterCriticalSection(&mutex->lock);
909   }
910   /*THROW_UNIMPLEMENTED; */
911 }
912
913 void xbt_os_cond_signal(xbt_os_cond_t cond)
914 {
915   int have_waiters;
916
917   EnterCriticalSection(&cond->waiters_count_lock);
918   have_waiters = cond->waiters_count > 0;
919   LeaveCriticalSection(&cond->waiters_count_lock);
920
921   if (have_waiters)
922     if (!SetEvent(cond->events[SIGNAL]))
923       THROW0(system_error, 0, "SetEvent failed");
924
925   xbt_os_thread_yield();
926 }
927
928 void xbt_os_cond_broadcast(xbt_os_cond_t cond)
929 {
930   int have_waiters;
931
932   EnterCriticalSection(&cond->waiters_count_lock);
933   have_waiters = cond->waiters_count > 0;
934   LeaveCriticalSection(&cond->waiters_count_lock);
935
936   if (have_waiters)
937     SetEvent(cond->events[BROADCAST]);
938 }
939
940 void xbt_os_cond_destroy(xbt_os_cond_t cond)
941 {
942   int error = 0;
943
944   if (!cond)
945     return;
946
947   if (!CloseHandle(cond->events[SIGNAL]))
948     error = 1;
949
950   if (!CloseHandle(cond->events[BROADCAST]))
951     error = 1;
952
953   DeleteCriticalSection(&cond->waiters_count_lock);
954
955   xbt_free(cond);
956
957   if (error)
958     THROW0(system_error, 0, "Error while destroying the condition");
959 }
960
961 typedef struct xbt_os_sem_ {
962   HANDLE h;
963   unsigned int value;
964   CRITICAL_SECTION value_lock;  /* protect access to value of the semaphore  */
965 } s_xbt_os_sem_t;
966
967 #ifndef INT_MAX
968 # define INT_MAX 32767          /* let's be safe by underestimating this value: this is for 16bits only */
969 #endif
970
971 xbt_os_sem_t xbt_os_sem_init(unsigned int value)
972 {
973   xbt_os_sem_t res;
974
975   if (value > INT_MAX)
976     THROW1(arg_error, value,
977            "Semaphore initial value too big: %ud cannot be stored as a signed int",
978            value);
979
980   res = (xbt_os_sem_t) xbt_new0(s_xbt_os_sem_t, 1);
981
982   if (!(res->h = CreateSemaphore(NULL, value, (long) INT_MAX, NULL))) {
983     THROW1(system_error, GetLastError(), "CreateSemaphore() failed: %s",
984            strerror(GetLastError()));
985     return NULL;
986   }
987
988   res->value = value;
989
990   InitializeCriticalSection(&(res->value_lock));
991
992   return res;
993 }
994
995 void xbt_os_sem_acquire(xbt_os_sem_t sem)
996 {
997   if (!sem)
998     THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
999
1000   /* wait failure */
1001   if (WAIT_OBJECT_0 != WaitForSingleObject(sem->h, INFINITE))
1002     THROW1(system_error, GetLastError(), "WaitForSingleObject() failed: %s",
1003            strerror(GetLastError()));
1004   EnterCriticalSection(&(sem->value_lock));
1005   sem->value--;
1006   LeaveCriticalSection(&(sem->value_lock));
1007 }
1008
1009 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
1010 {
1011   long seconds;
1012   long milliseconds;
1013   double end = timeout + xbt_os_time();
1014
1015   if (!sem)
1016     THROW0(arg_error, EINVAL, "Cannot acquire the NULL semaphore");
1017
1018   if (timeout < 0) {
1019     xbt_os_sem_acquire(sem);
1020   } else {                      /* timeout can be zero <-> try acquire ) */
1021
1022
1023     seconds = (long) floor(end);
1024     milliseconds = (long) ((end - seconds) * 1000);
1025     milliseconds += (seconds * 1000);
1026
1027     switch (WaitForSingleObject(sem->h, milliseconds)) {
1028     case WAIT_OBJECT_0:
1029       EnterCriticalSection(&(sem->value_lock));
1030       sem->value--;
1031       LeaveCriticalSection(&(sem->value_lock));
1032       return;
1033
1034     case WAIT_TIMEOUT:
1035       THROW2(timeout_error, GetLastError(),
1036              "semaphore %p wasn't signaled before timeout (%f)", sem,
1037              timeout);
1038       return;
1039
1040     default:
1041       THROW3(system_error, GetLastError(),
1042              "WaitForSingleObject(%p,%f) failed: %s", sem, timeout,
1043              strerror(GetLastError()));
1044     }
1045   }
1046 }
1047
1048 void xbt_os_sem_release(xbt_os_sem_t sem)
1049 {
1050   if (!sem)
1051     THROW0(arg_error, EINVAL, "Cannot release the NULL semaphore");
1052
1053   if (!ReleaseSemaphore(sem->h, 1, NULL))
1054     THROW1(system_error, GetLastError(), "ReleaseSemaphore() failed: %s",
1055            strerror(GetLastError()));
1056   EnterCriticalSection(&(sem->value_lock));
1057   sem->value++;
1058   LeaveCriticalSection(&(sem->value_lock));
1059 }
1060
1061 void xbt_os_sem_destroy(xbt_os_sem_t sem)
1062 {
1063   if (!sem)
1064     THROW0(arg_error, EINVAL, "Cannot destroy the NULL semaphore");
1065
1066   if (!CloseHandle(sem->h))
1067     THROW1(system_error, GetLastError(), "CloseHandle() failed: %s",
1068            strerror(GetLastError()));
1069
1070   DeleteCriticalSection(&(sem->value_lock));
1071
1072   xbt_free(sem);
1073
1074 }
1075
1076 void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
1077 {
1078   if (!sem)
1079     THROW0(arg_error, EINVAL, "Cannot get the value of the NULL semaphore");
1080
1081   EnterCriticalSection(&(sem->value_lock));
1082   *svalue = sem->value;
1083   LeaveCriticalSection(&(sem->value_lock));
1084 }
1085
1086 #endif