Logo AND Algorithmique Numérique Distribuée

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