Logo AND Algorithmique Numérique Distribuée

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