Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
8465beb8dd63d85003c889b590274ceff2691238
[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 #include <pthread.h>
26 #include <semaphore.h>
27
28 typedef struct xbt_os_thread_ {
29    pthread_t t;
30    char *name;
31    void *param;
32    pvoid_f_pvoid_t start_routine;
33    ex_ctx_t *exception;
34 } s_xbt_os_thread_t ;
35 static xbt_os_thread_t main_thread = NULL;
36
37 /* thread-specific data containing the xbt_os_thread_t structure */
38 static pthread_key_t xbt_self_thread_key;
39 static int thread_mod_inited = 0;
40
41 /* frees the xbt_os_thread_t corresponding to the current thread */
42 static void xbt_os_thread_free_thread_data(void*d){
43    free(d);
44 }
45
46 /* callback: context fetching */
47 static ex_ctx_t *_os_thread_ex_ctx(void) {
48   return xbt_os_thread_self()->exception;
49 }
50
51 /* callback: termination */
52 static void _os_thread_ex_terminate(xbt_ex_t * e) {
53   xbt_ex_display(e);
54
55   abort();
56   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
57 }
58
59 void xbt_os_thread_mod_init(void) {
60    int errcode;
61    
62    if (thread_mod_inited)
63      return;
64    
65    if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL)))
66      THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key");
67
68    main_thread=xbt_new(s_xbt_os_thread_t,1);
69    main_thread->name = (char*)"main";
70    main_thread->start_routine = NULL;
71    main_thread->param = NULL;
72    main_thread->exception = xbt_new(ex_ctx_t, 1);
73    XBT_CTX_INITIALIZE(main_thread->exception);
74
75    __xbt_ex_ctx = _os_thread_ex_ctx;
76    __xbt_ex_terminate = _os_thread_ex_terminate;
77
78    thread_mod_inited = 1;
79 }
80 void xbt_os_thread_mod_exit(void) {
81    /* FIXME: don't try to free our key on shutdown. 
82       Valgrind detects no leak if we don't, and whine if we try to */
83 //   int errcode;
84    
85 //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
86 //     THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
87 }
88
89 static void * wrapper_start_routine(void *s) {
90   xbt_os_thread_t t = s;   
91   int errcode;
92
93   if ((errcode=pthread_setspecific(xbt_self_thread_key,t)))
94     THROW0(system_error,errcode,
95            "pthread_setspecific failed for xbt_self_thread_key");   
96    
97   return (*(t->start_routine))(t->param);
98 }
99 xbt_os_thread_t xbt_os_thread_create(const char*name,
100                                      pvoid_f_pvoid_t start_routine,
101                                      void* param)  {
102    int errcode;
103
104    xbt_os_thread_t res_thread=xbt_new(s_xbt_os_thread_t,1);
105    res_thread->name = xbt_strdup(name);
106    res_thread->start_routine = start_routine;
107    res_thread->param = param;
108    res_thread->exception = xbt_new(ex_ctx_t, 1);
109    XBT_CTX_INITIALIZE(res_thread->exception);
110    
111    if ((errcode = pthread_create(&(res_thread->t), NULL, 
112                                  wrapper_start_routine, res_thread)))
113      THROW1(system_error,errcode, 
114             "pthread_create failed: %s",strerror(errcode));
115
116    return res_thread;
117 }
118
119 const char* xbt_os_thread_name(xbt_os_thread_t t) {
120    return t->name;
121 }
122
123 const char* xbt_os_thread_self_name(void) {
124    xbt_os_thread_t self = xbt_os_thread_self();
125    return self?self->name:"main";
126 }
127 void 
128 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
129         
130   int errcode;   
131   
132   if ((errcode = pthread_join(thread->t,thread_return)))
133     THROW1(system_error,errcode, "pthread_join failed: %s",
134            strerror(errcode));
135    if (thread->exception)
136      free(thread->exception);
137
138    if (thread == main_thread) /* just killed main thread */
139      main_thread = NULL;
140
141    free(thread);   
142 }                      
143
144 void xbt_os_thread_exit(int *retval) {
145    pthread_exit(retval);
146 }
147
148 xbt_os_thread_t xbt_os_thread_self(void) {
149   xbt_os_thread_t res;
150
151   if (!thread_mod_inited)
152     return NULL;
153   
154   res = pthread_getspecific(xbt_self_thread_key);
155   if (!res)
156     res = main_thread;
157
158   return res;
159 }
160
161 #include <sched.h>
162 void xbt_os_thread_yield(void) {
163    sched_yield();
164 }
165 void xbt_os_thread_cancel(xbt_os_thread_t t) {
166    pthread_cancel(t->t);
167 }
168 /****** mutex related functions ******/
169 typedef struct xbt_os_mutex_ {
170   /* KEEP IT IN SYNC WITH xbt_thread.c */
171    pthread_mutex_t m;
172 } s_xbt_os_mutex_t;
173
174 xbt_os_mutex_t xbt_os_mutex_init(void) {
175    xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
176    int errcode;
177    
178    if ((errcode = pthread_mutex_init(&(res->m),NULL)))
179      THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",
180             strerror(errcode));
181    
182    return res;
183 }
184
185 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) {
186    int errcode;
187    
188    if ((errcode=pthread_mutex_lock(&(mutex->m))))
189      THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s",
190             mutex, strerror(errcode));
191 }
192
193 void xbt_os_mutex_release(xbt_os_mutex_t mutex) {
194    int errcode;
195    
196    if ((errcode=pthread_mutex_unlock(&(mutex->m))))
197      THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s",
198             mutex, strerror(errcode));
199 }
200
201 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
202    int errcode;
203    
204    if (!mutex) return;
205    
206    if ((errcode=pthread_mutex_destroy(&(mutex->m))))
207      THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s",
208             mutex, strerror(errcode));
209    free(mutex);
210 }
211
212 /***** condition related functions *****/
213 typedef struct xbt_os_cond_ {
214   /* KEEP IT IN SYNC WITH xbt_thread.c */
215    pthread_cond_t c;
216 } s_xbt_os_cond_t;
217
218 xbt_os_cond_t xbt_os_cond_init(void) {
219    xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t,1);
220    int errcode;
221    if ((errcode=pthread_cond_init(&(res->c),NULL)))
222      THROW1(system_error,errcode,"pthread_cond_init() failed: %s",
223             strerror(errcode));
224
225    return res;
226 }
227
228 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
229    int errcode;
230    if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m))))
231      THROW3(system_error,errcode,"pthread_cond_wait(%p,%p) failed: %s",
232             cond,mutex, strerror(errcode));
233 }
234
235 #include <time.h>
236 #include <math.h>
237 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
238    int errcode;
239    struct timespec ts_end;
240    double end = delay + xbt_os_time();
241    
242    if (delay < 0) {
243       xbt_os_cond_wait(cond,mutex);
244    } else {
245       ts_end.tv_sec = (time_t) floor(end);
246       ts_end.tv_nsec = (long)  ( ( end - ts_end.tv_sec) * 1000000000);
247       DEBUG3("pthread_cond_timedwait(%p,%p,%p)",&(cond->c),&(mutex->m), &ts_end);
248       switch ( (errcode=pthread_cond_timedwait(&(cond->c),&(mutex->m), &ts_end)) ) {
249        case 0:
250          return;
251        case ETIMEDOUT:
252          THROW3(timeout_error,errcode,"condition %p (mutex %p) wasn't signaled before timeout (%f)",
253                 cond,mutex, delay);
254        default:
255          THROW4(system_error,errcode,"pthread_cond_timedwait(%p,%p,%f) failed: %s",
256                 cond,mutex, delay, strerror(errcode));
257       }   
258    }
259 }
260
261 void xbt_os_cond_signal(xbt_os_cond_t cond) {
262    int errcode;
263    if ((errcode=pthread_cond_signal(&(cond->c))))
264      THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s",
265             cond, strerror(errcode));
266 }
267          
268 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
269    int errcode;
270    if ((errcode=pthread_cond_broadcast(&(cond->c))))
271      THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s",
272             cond, strerror(errcode));
273 }
274 void xbt_os_cond_destroy(xbt_os_cond_t cond){
275    int errcode;
276
277    if (!cond) return;
278
279    if ((errcode=pthread_cond_destroy(&(cond->c))))
280      THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s",
281             cond, strerror(errcode));
282    free(cond);
283 }
284
285 void *xbt_os_thread_getparam(void) {
286    xbt_os_thread_t t = xbt_os_thread_self();
287    return t?t->param:NULL;
288 }
289
290 typedef struct xbt_os_sem_ {
291    sem_t s;
292 }s_xbt_os_sem_t ;
293
294 xbt_os_sem_t
295 xbt_os_sem_init(unsigned int value)
296 {
297         xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t,1);
298         
299         if(sem_init(&(res->s),0,value) < 0)
300                 THROW1(system_error,errno,"sem_init() failed: %s",
301             strerror(errno));
302    
303    return res;
304 }
305
306 void 
307 xbt_os_sem_acquire(xbt_os_sem_t sem)
308 {
309         if(!sem)
310                 THROW1(arg_error,EINVAL,"xbt_os_sem_acquire() failed: %s",
311             strerror(EINVAL));
312         
313         if(sem_wait(&(sem->s)) < 0)
314                 THROW1(system_error,errno,"sem_wait() failed: %s",
315             strerror(errno));            
316 }
317
318 void xbt_os_sem_timedacquire(xbt_os_sem_t sem,double timeout)
319 {
320         /* mac os x have not the sem_timedwait() function */
321         #ifndef HAVE_SEM_TIMEDWAIT
322         THROW_UNIMPLEMENTED;
323         #else
324         int errcode;
325         struct timespec ts_end;
326         double end = timeout + xbt_os_time();
327         
328         if(!sem)
329                 THROW1(arg_error,EINVAL,"xbt_os_sem_timedacquire() failed: %s",strerror(EINVAL));
330         
331         if (timeout < 0) 
332         {
333                 xbt_os_sem_acquire(sem);
334         } 
335         else 
336         {
337                 ts_end.tv_sec = (time_t) floor(end);
338                 ts_end.tv_nsec = (long)  ( ( end - ts_end.tv_sec) * 1000000000);
339                 DEBUG2("sem_timedwait(%p,%p)",&(sem->s),&ts_end);
340         
341                 switch ((errcode=sem_timedwait(&(sem->s),&ts_end)))
342                 {
343                         case 0:
344                         return;
345                         
346                         case ETIMEDOUT:
347                         THROW2(timeout_error,errcode,"semaphore %p wasn't signaled before timeout (%f)",sem,timeout);
348                         
349                         default:
350                         THROW3(system_error,errcode,"sem_timedwait(%p,%f) failed: %s",sem,timeout, strerror(errcode));
351                 }   
352         }
353         #endif
354 }
355
356 void 
357 xbt_os_sem_release(xbt_os_sem_t sem)
358 {
359         if(!sem)
360                 THROW1(arg_error,EINVAL,"xbt_os_sem_release() failed: %s",
361             strerror(EINVAL));
362         
363         if(sem_post(&(sem->s)) < 0)
364                 THROW1(system_error,errno,"sem_post() failed: %s",
365             strerror(errno));            
366 }
367
368 void
369 xbt_os_sem_destroy(xbt_os_sem_t sem)
370 {
371         if(!sem)
372                 THROW1(arg_error,EINVAL,"xbt_os_sem_destroy() failed: %s",
373             strerror(EINVAL));
374             
375         if(sem_destroy(&(sem->s)) < 0)
376                 THROW1(system_error,errno,"sem_destroy() failed: %s",
377             strerror(errno));
378 }
379
380 void
381 xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue)
382 {
383         if(!sem)
384                 THROW1(arg_error,EINVAL,"xbt_os_sem_getvalue() failed: %s",
385             strerror(EINVAL));
386             
387         if(sem_getvalue(&(sem->s),svalue) < 0)
388                 THROW1(system_error,errno,"sem_getvalue() failed: %s",
389             strerror(errno));
390 }
391
392 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
393
394 #elif defined(WIN32)
395
396 #include <math.h>
397
398 typedef struct xbt_os_thread_ {
399   char *name;
400   HANDLE handle;                  /* the win thread handle        */
401   unsigned long id;               /* the win thread id            */
402   pvoid_f_pvoid_t start_routine;
403   void* param;
404 } s_xbt_os_thread_t ;
405
406 /* so we can specify the size of the stack of the threads */
407 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
408 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
409 #endif
410
411 /* the default size of the stack of the threads (in bytes)*/
412 #define XBT_DEFAULT_THREAD_STACK_SIZE   4096
413
414 /* key to the TLS containing the xbt_os_thread_t structure */
415 static unsigned long xbt_self_thread_key;
416
417 void xbt_os_thread_mod_init(void) {
418    xbt_self_thread_key = TlsAlloc();
419 }
420 void xbt_os_thread_mod_exit(void) {
421    
422    if (!TlsFree(xbt_self_thread_key)) 
423      THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
424 }
425
426 static DWORD WINAPI  wrapper_start_routine(void *s) {
427   xbt_os_thread_t t = (xbt_os_thread_t)s;
428   void* rv;
429  
430     if(!TlsSetValue(xbt_self_thread_key,t))
431      THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
432    
433    rv = (*(t->start_routine))(t->param);
434
435    return *((DWORD*)rv);
436 }
437
438
439 xbt_os_thread_t xbt_os_thread_create(const char *name,pvoid_f_pvoid_t start_routine,
440                                void* param)  {
441    
442    xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1);
443
444    t->name = xbt_strdup(name);
445    t->start_routine = start_routine ;
446    t->param = param;
447    
448    t->handle = CreateThread(NULL,XBT_DEFAULT_THREAD_STACK_SIZE,
449                             (LPTHREAD_START_ROUTINE)wrapper_start_routine,
450                             t,STACK_SIZE_PARAM_IS_A_RESERVATION,&(t->id));
451         
452    if(!t->handle) {
453      xbt_free(t);
454      THROW0(system_error,(int)GetLastError(),"CreateThread failed");
455    }
456    
457    return t;
458 }
459
460 const char* xbt_os_thread_name(xbt_os_thread_t t) {
461    return t->name;
462 }
463
464 const char* xbt_os_thread_self_name(void) {
465    xbt_os_thread_t t = xbt_os_thread_self();
466    return t?t->name:"main";
467 }
468
469 void 
470 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
471
472         if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))  
473                 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
474                 
475         if(thread_return){
476                 
477                 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
478                         THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
479         }
480         
481         CloseHandle(thread->handle);
482         free(thread->name);
483         free(thread);
484 }
485
486 void xbt_os_thread_exit(int *retval) {
487    if(retval)
488         ExitThread(*retval);
489    else
490         ExitThread(0);
491 }
492
493 xbt_os_thread_t xbt_os_thread_self(void) {
494    return TlsGetValue(xbt_self_thread_key);
495 }
496
497 void *xbt_os_thread_getparam(void) {
498    xbt_os_thread_t t = xbt_os_thread_self();
499    return t->param;
500 }
501
502
503 void xbt_os_thread_yield(void) {
504     Sleep(0);
505 }
506 void xbt_os_thread_cancel(xbt_os_thread_t t) {
507    THROW_UNIMPLEMENTED;
508 }
509
510 /****** mutex related functions ******/
511 typedef struct xbt_os_mutex_ {
512   /* KEEP IT IN SYNC WITH xbt_thread.c */
513    CRITICAL_SECTION lock;   
514 } s_xbt_os_mutex_t;
515
516 xbt_os_mutex_t xbt_os_mutex_init(void) {
517    xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
518
519    /* initialize the critical section object */
520    InitializeCriticalSection(&(res->lock));
521    
522    return res;
523 }
524
525 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) {
526
527    EnterCriticalSection(& mutex->lock);
528 }
529
530 void xbt_os_mutex_release(xbt_os_mutex_t mutex) {
531
532    LeaveCriticalSection (& mutex->lock);
533
534 }
535
536 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
537
538    if (!mutex) return;
539    
540    DeleteCriticalSection(& mutex->lock);                
541    free(mutex);
542 }
543
544 /***** condition related functions *****/
545  enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
546     SIGNAL = 0,
547     BROADCAST = 1,
548     MAX_EVENTS = 2
549  };
550
551 typedef struct xbt_os_cond_ {
552   /* KEEP IT IN SYNC WITH xbt_thread.c */
553    HANDLE events[MAX_EVENTS];
554    
555    unsigned int waiters_count;           /* the number of waiters                        */
556    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
557 } s_xbt_os_cond_t;
558
559 xbt_os_cond_t xbt_os_cond_init(void) {
560
561    xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1);
562         
563    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
564         
565    /* initialize the critical section object */
566    InitializeCriticalSection(& res->waiters_count_lock);
567         
568    res->waiters_count = 0;
569         
570    /* Create an auto-reset event */
571    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); 
572         
573    if(!res->events[SIGNAL]){
574       DeleteCriticalSection(& res->waiters_count_lock);
575       free(res);
576       THROW0(system_error,0,"CreateEvent failed for the signals");
577    }
578         
579    /* Create a manual-reset event. */
580    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
581         
582    if(!res->events[BROADCAST]){
583                 
584       DeleteCriticalSection(& res->waiters_count_lock);         
585       CloseHandle(res->events[SIGNAL]);
586       free(res); 
587       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
588    }
589
590    return res;
591 }
592
593 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
594         
595    unsigned long wait_result;
596    int is_last_waiter;
597
598    /* lock the threads counter and increment it */
599    EnterCriticalSection (& cond->waiters_count_lock);
600    cond->waiters_count++;
601    LeaveCriticalSection (& cond->waiters_count_lock);
602                 
603    /* unlock the mutex associate with the condition */
604    LeaveCriticalSection (& mutex->lock);
605         
606    /* wait for a signal (broadcast or no) */
607    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
608         
609    if(wait_result == WAIT_FAILED)
610      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
611         
612    /* we have a signal lock the condition */
613    EnterCriticalSection (& cond->waiters_count_lock);
614    cond->waiters_count--;
615         
616    /* it's the last waiter or it's a broadcast ? */
617    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
618         
619    LeaveCriticalSection (& cond->waiters_count_lock);
620         
621    /* yes it's the last waiter or it's a broadcast
622     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
623     * by the system. 
624     */
625    if (is_last_waiter)
626       if(!ResetEvent (cond->events[BROADCAST]))
627         THROW0(system_error,0,"ResetEvent failed");
628         
629    /* relock the mutex associated with the condition in accordance with the posix thread specification */
630    EnterCriticalSection (& mutex->lock);
631 }
632 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
633    
634          unsigned long wait_result = WAIT_TIMEOUT;
635    int is_last_waiter;
636    unsigned long end = (unsigned long)(delay * 1000);
637
638
639    if (delay < 0) {
640       xbt_os_cond_wait(cond,mutex);
641    } else {
642           DEBUG3("xbt_cond_timedwait(%p,%p,%ul)",&(cond->events),&(mutex->lock),end);
643
644    /* lock the threads counter and increment it */
645    EnterCriticalSection (& cond->waiters_count_lock);
646    cond->waiters_count++;
647    LeaveCriticalSection (& cond->waiters_count_lock);
648                 
649    /* unlock the mutex associate with the condition */
650    LeaveCriticalSection (& mutex->lock);
651    /* wait for a signal (broadcast or no) */
652         
653    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, end);
654         
655    switch(wait_result) {
656      case WAIT_TIMEOUT:
657         THROW3(timeout_error,GetLastError(),"condition %p (mutex %p) wasn't signaled before timeout (%f)",cond,mutex, delay);
658         case WAIT_FAILED:
659      THROW0(system_error,GetLastError(),"WaitForMultipleObjects failed, so we cannot wait on the condition");
660    }
661         
662    /* we have a signal lock the condition */
663    EnterCriticalSection (& cond->waiters_count_lock);
664    cond->waiters_count--;
665         
666    /* it's the last waiter or it's a broadcast ? */
667    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
668         
669    LeaveCriticalSection (& cond->waiters_count_lock);
670         
671    /* yes it's the last waiter or it's a broadcast
672     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
673     * by the system. 
674     */
675    if (is_last_waiter)
676       if(!ResetEvent (cond->events[BROADCAST]))
677         THROW0(system_error,0,"ResetEvent failed");
678         
679    /* relock the mutex associated with the condition in accordance with the posix thread specification */
680    EnterCriticalSection (& mutex->lock);
681    }
682         /*THROW_UNIMPLEMENTED;*/
683 }
684
685 void xbt_os_cond_signal(xbt_os_cond_t cond) {
686    int have_waiters;
687
688    EnterCriticalSection (& cond->waiters_count_lock);
689    have_waiters = cond->waiters_count > 0;
690    LeaveCriticalSection (& cond->waiters_count_lock);
691         
692    if (have_waiters)
693      if(!SetEvent(cond->events[SIGNAL]))
694        THROW0(system_error,0,"SetEvent failed");
695        
696    xbt_os_thread_yield();
697 }
698
699 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
700    int have_waiters;
701
702    EnterCriticalSection (& cond->waiters_count_lock);
703    have_waiters = cond->waiters_count > 0;
704    LeaveCriticalSection (& cond->waiters_count_lock);
705         
706    if (have_waiters)
707      SetEvent(cond->events[BROADCAST]);
708 }
709
710 void xbt_os_cond_destroy(xbt_os_cond_t cond){
711    int error = 0;
712    
713    if (!cond) return;
714    
715    if(!CloseHandle(cond->events[SIGNAL]))
716      error = 1;
717         
718    if(!CloseHandle(cond->events[BROADCAST]))
719      error = 1;
720         
721    DeleteCriticalSection(& cond->waiters_count_lock);
722         
723    xbt_free(cond);
724    
725    if (error)
726      THROW0(system_error,0,"Error while destroying the condition");
727 }
728
729 typedef struct xbt_os_sem_ {
730    HANDLE h;
731    unsigned int value;
732    CRITICAL_SECTION value_lock;  /* protect access to value of the semaphore  */
733 }s_xbt_os_sem_t ;
734
735 xbt_os_sem_t
736 xbt_os_sem_init(unsigned int value)
737 {
738         xbt_os_sem_t res;
739         
740         if(value > INT_MAX)
741         THROW1(arg_error,EINVAL,"xbt_os_sem_init() failed: %s",
742             strerror(EINVAL));
743         
744         res = (xbt_os_sem_t)xbt_new0(s_xbt_os_sem_t,1);
745         
746         if(!(res->h = CreateSemaphore(NULL,value,(long)INT_MAX,NULL))) {
747                 THROW1(system_error,GetLastError(),"CreateSemaphore() failed: %s",
748             strerror(GetLastError()));
749             return NULL;
750         }
751   
752         res->value = value;
753         
754         InitializeCriticalSection(&(res->value_lock));
755    
756         return res;
757 }
758
759 void 
760 xbt_os_sem_acquire(xbt_os_sem_t sem)
761 {
762         if(!sem)
763                 THROW1(arg_error,EINVAL,"xbt_os_sem_acquire() failed: %s",
764             strerror(EINVAL));  
765
766         /* wait failure */
767         if(WAIT_OBJECT_0 != WaitForSingleObject(sem->h,INFINITE))
768                 THROW1(system_error,GetLastError(),"WaitForSingleObject() failed: %s",
769                 strerror(GetLastError()));
770         EnterCriticalSection(&(sem->value_lock));
771         sem->value--;
772         LeaveCriticalSection(&(sem->value_lock));
773 }
774
775 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
776 {
777         long seconds;
778         long milliseconds;
779         double end = timeout + xbt_os_time();
780         
781         if(!sem)
782                 THROW1(arg_error,EINVAL,"xbt_os_sem_timedacquire() failed: %s",
783             strerror(EINVAL));  
784         
785          if (timeout < 0) 
786         {
787                 xbt_os_sem_acquire(sem);
788         } 
789         else 
790         {
791                 
792                 seconds = (long) floor(end);
793                 milliseconds = (long)( ( end - seconds) * 1000);
794                 milliseconds += (seconds * 1000);
795                 
796                 switch(WaitForSingleObject(sem->h,milliseconds))
797                 {
798                         case WAIT_OBJECT_0:
799                         EnterCriticalSection(&(sem->value_lock));
800                         sem->value--;
801                         LeaveCriticalSection(&(sem->value_lock));
802                         return;
803                 
804                         case WAIT_TIMEOUT:
805                         THROW2(timeout_error,GetLastError(),"semaphore %p wasn't signaled before timeout (%f)",sem,timeout);
806                         return;
807                 
808                         default:
809                         
810                         THROW3(system_error,GetLastError(),"WaitForSingleObject(%p,%f) failed: %s",sem,timeout, strerror(GetLastError()));
811                 }
812         }
813 }
814
815 void 
816 xbt_os_sem_release(xbt_os_sem_t sem)
817 {
818         if(!sem)
819                 THROW1(arg_error,EINVAL,"xbt_os_sem_post() failed: %s",
820             strerror(EINVAL));
821         
822         if(!ReleaseSemaphore(sem->h,1, NULL)) 
823                 THROW1(system_error,GetLastError(),"ReleaseSemaphore() failed: %s",
824                 strerror(GetLastError()));
825         EnterCriticalSection (&(sem->value_lock));
826         sem->value++;
827         LeaveCriticalSection(&(sem->value_lock));
828 }
829
830 void
831 xbt_os_sem_destroy(xbt_os_sem_t sem)
832 {
833         if(!sem)
834                 THROW1(arg_error,EINVAL,"xbt_os_sem_destroy() failed: %s",
835             strerror(EINVAL));
836         
837         if(!CloseHandle(sem->h)) 
838                 THROW1(system_error,GetLastError(),"CloseHandle() failed: %s",
839                 strerror(GetLastError()));
840          
841          DeleteCriticalSection(&(sem->value_lock));
842                 
843          xbt_free(sem);     
844                 
845 }
846
847 void
848 xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue)
849 {
850         if(!sem)
851                 THROW1(arg_error,EINVAL,"xbt_os_sem_get_value() failed: %s",
852             strerror(EINVAL));
853         
854         EnterCriticalSection(&(sem->value_lock));  
855         *svalue = sem->value;
856         LeaveCriticalSection(&(sem->value_lock));
857 }
858
859 #endif