Logo AND Algorithmique Numérique Distribuée

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