Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a6a22864979c9919d9bacaa1d4725bbb6c96001f
[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 /* use named sempahore instead */
29 #ifndef HAVE_SEM_WAIT
30 #  define MAX_SEM_NAME ((size_t)13)
31    static int __next_sem_ID = 0;
32    static pthread_mutex_t __next_sem_ID_lock;
33 #endif
34
35 typedef struct xbt_os_thread_ {
36    pthread_t t;
37    char *name;
38    void *param;
39    pvoid_f_pvoid_t start_routine;
40    ex_ctx_t *exception;
41 } s_xbt_os_thread_t ;
42 static xbt_os_thread_t main_thread = NULL;
43
44 /* thread-specific data containing the xbt_os_thread_t structure */
45 static pthread_key_t xbt_self_thread_key;
46 static int thread_mod_inited = 0;
47
48 /* frees the xbt_os_thread_t corresponding to the current thread */
49 static void xbt_os_thread_free_thread_data(void*d){
50    free(d);
51 }
52
53 /* callback: context fetching */
54 static ex_ctx_t *_os_thread_ex_ctx(void) {
55   return xbt_os_thread_self()->exception;
56 }
57
58 /* callback: termination */
59 static void _os_thread_ex_terminate(xbt_ex_t * e) {
60   xbt_ex_display(e);
61
62   abort();
63   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
64 }
65
66 void xbt_os_thread_mod_init(void) {
67    int errcode;
68
69    if (thread_mod_inited)
70      return;
71
72    if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL)))
73      THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key");
74
75    main_thread=xbt_new(s_xbt_os_thread_t,1);
76    main_thread->name = (char*)"main";
77    main_thread->start_routine = NULL;
78    main_thread->param = NULL;
79    main_thread->exception = xbt_new(ex_ctx_t, 1);
80    XBT_CTX_INITIALIZE(main_thread->exception);
81
82    __xbt_ex_ctx = _os_thread_ex_ctx;
83    __xbt_ex_terminate = _os_thread_ex_terminate;
84
85    #ifndef HAVE_SEM_WAIT
86
87    /* initialize the mutex use to protect the incrementation of the variable __next_sem_ID
88     * used to build the name of the named sempahore
89     */
90    if ((errcode = pthread_mutex_init(&__next_sem_ID_lock,NULL)))
91      THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",strerror(errcode));
92
93    #endif
94
95    thread_mod_inited = 1;
96 }
97 void xbt_os_thread_mod_exit(void) {
98    /* FIXME: don't try to free our key on shutdown.
99       Valgrind detects no leak if we don't, and whine if we try to */
100 //   int errcode;
101
102 //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
103 //     THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
104 }
105
106 static void * wrapper_start_routine(void *s) {
107   xbt_os_thread_t t = s;
108   int errcode;
109
110   if ((errcode=pthread_setspecific(xbt_self_thread_key,t)))
111     THROW0(system_error,errcode,
112            "pthread_setspecific failed for xbt_self_thread_key");
113
114   return (*(t->start_routine))(t->param);
115 }
116
117 xbt_os_thread_t xbt_os_thread_create(const char*name,
118                                      pvoid_f_pvoid_t start_routine,
119                                      void* param)  {
120    int errcode;
121
122    xbt_os_thread_t res_thread=xbt_new(s_xbt_os_thread_t,1);
123    res_thread->name = xbt_strdup(name);
124    res_thread->start_routine = start_routine;
125    res_thread->param = param;
126    res_thread->exception = xbt_new(ex_ctx_t, 1);
127    XBT_CTX_INITIALIZE(res_thread->exception);
128
129    if ((errcode = pthread_create(&(res_thread->t), NULL,
130                                  wrapper_start_routine, res_thread)))
131      THROW1(system_error,errcode,
132             "pthread_create failed: %s",strerror(errcode));
133
134    return res_thread;
135 }
136
137 const char* xbt_os_thread_name(xbt_os_thread_t t) {
138    return t->name;
139 }
140
141 const char* xbt_os_thread_self_name(void) {
142    xbt_os_thread_t self = xbt_os_thread_self();
143    return self?self->name:"main";
144 }
145 void
146 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
147
148   int errcode;
149
150   if ((errcode = pthread_join(thread->t,thread_return)))
151     THROW1(system_error,errcode, "pthread_join failed: %s",
152            strerror(errcode));
153    if (thread->exception)
154      free(thread->exception);
155
156    if (thread == main_thread) /* just killed main thread */
157      main_thread = NULL;
158
159    free(thread);
160 }
161
162 void xbt_os_thread_exit(int *retval) {
163    pthread_exit(retval);
164 }
165
166 xbt_os_thread_t xbt_os_thread_self(void) {
167   xbt_os_thread_t res;
168
169   if (!thread_mod_inited)
170     return NULL;
171
172   res = pthread_getspecific(xbt_self_thread_key);
173   if (!res)
174     res = main_thread;
175
176   return res;
177 }
178
179 #include <sched.h>
180 void xbt_os_thread_yield(void) {
181    sched_yield();
182 }
183 void xbt_os_thread_cancel(xbt_os_thread_t t) {
184    pthread_cancel(t->t);
185 }
186 /****** mutex related functions ******/
187 typedef struct xbt_os_mutex_ {
188   /* KEEP IT IN SYNC WITH xbt_thread.c */
189    pthread_mutex_t m;
190 } s_xbt_os_mutex_t;
191
192 #include <time.h>
193 #include <math.h>
194
195 xbt_os_mutex_t xbt_os_mutex_init(void) {
196    xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
197    int errcode;
198
199    if ((errcode = pthread_mutex_init(&(res->m),NULL)))
200      THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",
201             strerror(errcode));
202
203    return res;
204 }
205
206 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) {
207    int errcode;
208
209    if ((errcode=pthread_mutex_lock(&(mutex->m))))
210      THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s",
211             mutex, strerror(errcode));
212 }
213
214
215
216 #ifndef HAVE_PTHREAD_MUTEX_TIMEDLOCK
217 /* if the function is not availabled or if is MAC OS X use pthread_mutex_trylock() to define
218  * it.
219  */
220 #include <time.h> /* declaration of the timespec structure and of the nanosleep() function */
221 int pthread_mutex_timedlock(pthread_mutex_t * mutex, const struct timespec * abs_timeout)
222 {
223         int rv;
224         long ellapsed_time = 0;
225         struct timespec ts;
226
227         do
228         {
229                 /* the mutex could not be acquired because it was already locked by an other thread */
230                 rv = pthread_mutex_trylock(mutex);
231
232                 ts.tv_sec = 0;
233                 ts.tv_nsec = 2.5e7 /* (25 ms (2 context switch + 5 ms)) */;
234
235                 do
236                 {
237                         nanosleep(&ts, &ts);
238                 }while(EINTR == errno);
239
240                 ellapsed_time += ts.tv_nsec;
241
242         }
243         while (/* locked */ (EBUSY == rv) && /* !timeout */ (ellapsed_time < ((long)(abs_timeout->tv_sec * 1e9) + abs_timeout->tv_nsec)));
244
245         return (EBUSY == rv) ? ETIMEDOUT : rv;
246 }
247
248 #endif
249
250 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay) {
251    int errcode;
252    struct timespec ts_end;
253    double end = delay + xbt_os_time();
254         
255    if (delay < 0) {
256       xbt_os_mutex_acquire(mutex);
257    }
258    else if(!delay /* equals 0 */)
259         {
260                 if ((errcode=pthread_mutex_trylock(&(mutex->m))))
261                 THROW2(system_error,errcode,"pthread_mutex_trylock(%p) failed: %s",mutex, strerror(errcode));
262                 
263    } else {
264       ts_end.tv_sec = (time_t) floor(end);
265       ts_end.tv_nsec = (long)  ( ( end - ts_end.tv_sec) * 1000000000);
266       DEBUG2("pthread_mutex_timedlock(%p,%p)",&(mutex->m), &ts_end);
267
268    switch ((errcode=pthread_mutex_timedlock(&(mutex->m),&ts_end)))
269      {
270         case 0:
271                 return;
272
273                 case ETIMEDOUT:
274                 THROW2(timeout_error,errcode,"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_WAIT
380    char* name;
381    sem_t* s;
382    #else
383    sem_t s;
384    #endif
385 }s_xbt_os_sem_t ;
386
387 xbt_os_sem_t
388 xbt_os_sem_init(unsigned int value)
389 {
390         xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t,1);
391         int errcode;
392
393         /* On MAC OS X, it seems that the sem_init is failing with ENOSYS,
394          * which means the sem_init function is not implemented use sem_open()
395          * instead
396          */
397         #ifndef HAVE_SEM_INIT
398         res->name = (char*) calloc(MAX_SEM_NAME + 1,sizeof(char));
399
400         if((errcode = pthread_mutex_lock(&__next_sem_ID_lock)))
401                 THROW1(system_error,errcode,"pthread_mutex_lock() failed: %s", strerror(errcode));
402
403         __next_sem_ID++;
404
405         if((errcode = pthread_mutex_unlock(&__next_sem_ID_lock)))
406                 THROW1(system_error,errcode,"pthread_mutex_unlock() failed: %s", strerror(errcode));
407
408         sprintf(res->name,"/%d.%d",(*xbt_getpid)(),__next_sem_ID);
409
410         if((res->s = sem_open(res->name, O_CREAT, 0644, value)) == (sem_t*)SEM_FAILED)
411                 THROW1(system_error,errno,"sem_open() failed: %s",strerror(errno));
412         
413         if(sem_unlink(res->name) < 0)
414                 THROW1(system_error,errno,"sem_unlink() failed: %s", strerror(errno));
415
416
417         #else
418         /* sem_init() is implemented, use it */
419         if(sem_init(&(res->s),0,value) < 0)
420                 THROW1(system_error,errno,"sem_init() failed: %s",
421             strerror(errno));
422         #endif
423
424    return res;
425 }
426
427 void
428 xbt_os_sem_acquire(xbt_os_sem_t sem)
429 {
430         if(!sem)
431                 THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore");
432         #ifndef HAVE_SEM_WAIT
433         if(sem_wait((sem->s)) < 0)
434                 THROW1(system_error,errno,"sem_wait() failed: %s",
435             strerror(errno));
436         #else
437         if(sem_wait(&(sem->s)) < 0)
438                 THROW1(system_error,errno,"sem_wait() failed: %s",
439             strerror(errno));
440         #endif
441 }
442
443 #ifndef HAVE_SEM_TIMEDWAIT
444 /* if the function is not availabled or if is MAC OS X use sem_trywait() to define
445  * it.
446  */
447 #include <time.h> /* declaration of the timespec structure and of the nanosleep() function */
448 int sem_timedwait(sem_t* sem, const struct timespec * abs_timeout)
449 {
450         int rv;
451         long ellapsed_time = 0;
452         struct timespec ts;
453
454         do
455         {
456                 rv = sem_trywait(sem);
457                 ts.tv_sec = 0;
458                 ts.tv_nsec = 2.5e7 /* (25 ms (2 * context switch + 5 ms)) */;
459
460                 do
461                 {
462                         nanosleep(&ts, &ts);
463                 }while(EINTR == errno);
464
465                 ellapsed_time += ts.tv_nsec;
466
467         }
468         while(/* locked */ (EAGAIN == rv) && /* !timeout */ ellapsed_time < ((long)(abs_timeout->tv_sec * 1e9) + abs_timeout->tv_nsec));
469
470         return (EAGAIN == rv) ? ETIMEDOUT : rv;
471 }
472
473 #endif
474
475 void xbt_os_sem_timedacquire(xbt_os_sem_t sem,double timeout)
476 {
477         int errcode;
478         struct timespec ts_end;
479         double end = timeout + xbt_os_time();
480
481         if(!sem)
482                 THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore");
483
484         if (timeout < 0)
485         {
486                 xbt_os_sem_acquire(sem);
487         }
488         else if(!timeout)
489         {
490                 #ifndef HAVE_SEM_TIMEDWAIT
491                 if(sem_trywait(sem->s) < 0)
492                         THROW2(system_error,errno,"sem_trywait(%p) failed: %s",sem,strerror(errno));
493                 #else
494                 if(sem_trywait(&(sem->s)) < 0)
495                         THROW2(system_error,errno,"sem_trywait(%p) failed: %s",sem,strerror(errno));
496                 #endif          
497         }
498         else
499         {
500                 ts_end.tv_sec = (time_t) floor(end);
501                 ts_end.tv_nsec = (long)  ( ( end - ts_end.tv_sec) * 1000000000);
502                 DEBUG2("sem_timedwait(%p,%p)",&(sem->s),&ts_end);
503
504                 #ifndef HAVE_SEM_WAIT
505                 switch ((errcode = sem_timedwait(sem->s,&ts_end)))
506                 #else
507                 switch ((errcode = sem_timedwait(&(sem->s),&ts_end)))
508                 #endif
509                 {
510                         case 0:
511                         return;
512
513                         case ETIMEDOUT:
514                         THROW2(timeout_error,errcode,"semaphore %p wasn't signaled before timeout (%f)",sem,timeout);
515
516                         default:
517                         THROW3(system_error,errcode,"sem_timedwait(%p,%f) failed: %s",sem,timeout, strerror(errcode));
518                 }
519         }
520
521 }
522
523 void
524 xbt_os_sem_release(xbt_os_sem_t sem)
525 {
526         if(!sem)
527                 THROW0(arg_error,EINVAL,"Cannot release of the NULL semaphore");
528
529         #ifndef HAVE_SEM_WAIT
530         if(sem_post((sem->s)) < 0)
531                 THROW1(system_error,errno,"sem_post() failed: %s",
532             strerror(errno));
533         #else
534         if(sem_post(&(sem->s)) < 0)
535                 THROW1(system_error,errno,"sem_post() failed: %s",
536             strerror(errno));
537         #endif
538 }
539
540 void
541 xbt_os_sem_destroy(xbt_os_sem_t sem)
542 {
543         if(!sem)
544                 THROW0(arg_error,EINVAL,"Cannot destroy the NULL sempahore");
545
546         #ifndef HAVE_SEM_WAIT
547         /* MAC OS X does not implement the sem_init() function so,
548          * we use the named semaphore (sem_open)
549          */
550         if(sem_close((sem->s)) < 0)
551                 THROW1(system_error,errno,"sem_close() failed: %s",
552             strerror(errno));
553
554         xbt_free(sem->name);
555
556         #else
557         if(sem_destroy(&(sem->s)) < 0)
558                 THROW1(system_error,errno,"sem_destroy() failed: %s",
559             strerror(errno));
560         #endif
561
562         xbt_free(sem);
563 }
564
565 void
566 xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue)
567 {
568         if(!sem)
569                 THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore");
570
571         #ifndef HAVE_SEM_WAIT
572         if(sem_getvalue((sem->s),svalue) < 0)
573                 THROW1(system_error,errno,"sem_getvalue() failed: %s",
574             strerror(errno));
575         #else
576         if(sem_getvalue(&(sem->s),svalue) < 0)
577                 THROW1(system_error,errno,"sem_getvalue() failed: %s",
578             strerror(errno));
579         #endif
580 }
581
582 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
583
584 #elif defined(WIN32)
585
586 #include <math.h>
587
588 typedef struct xbt_os_thread_ {
589   char *name;
590   HANDLE handle;                  /* the win thread handle        */
591   unsigned long id;               /* the win thread id            */
592   pvoid_f_pvoid_t start_routine;
593   void* param;
594 } s_xbt_os_thread_t ;
595
596 /* so we can specify the size of the stack of the threads */
597 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
598 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
599 #endif
600
601 /* the default size of the stack of the threads (in bytes)*/
602 #define XBT_DEFAULT_THREAD_STACK_SIZE   4096
603
604 /* key to the TLS containing the xbt_os_thread_t structure */
605 static unsigned long xbt_self_thread_key;
606
607 void xbt_os_thread_mod_init(void) {
608    xbt_self_thread_key = TlsAlloc();
609 }
610 void xbt_os_thread_mod_exit(void) {
611
612    if (!TlsFree(xbt_self_thread_key))
613      THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
614 }
615
616 static DWORD WINAPI  wrapper_start_routine(void *s) {
617   xbt_os_thread_t t = (xbt_os_thread_t)s;
618   void* rv;
619
620     if(!TlsSetValue(xbt_self_thread_key,t))
621      THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
622
623    rv = (*(t->start_routine))(t->param);
624
625    return *((DWORD*)rv);
626 }
627
628
629 xbt_os_thread_t xbt_os_thread_create(const char *name,pvoid_f_pvoid_t start_routine,
630                                void* param)  {
631
632    xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1);
633
634    t->name = xbt_strdup(name);
635    t->start_routine = start_routine ;
636    t->param = param;
637
638    t->handle = CreateThread(NULL,XBT_DEFAULT_THREAD_STACK_SIZE,
639                             (LPTHREAD_START_ROUTINE)wrapper_start_routine,
640                             t,STACK_SIZE_PARAM_IS_A_RESERVATION,&(t->id));
641
642    if(!t->handle) {
643      xbt_free(t);
644      THROW0(system_error,(int)GetLastError(),"CreateThread failed");
645    }
646
647    return t;
648 }
649
650 const char* xbt_os_thread_name(xbt_os_thread_t t) {
651    return t->name;
652 }
653
654 const char* xbt_os_thread_self_name(void) {
655    xbt_os_thread_t t = xbt_os_thread_self();
656    return t?t->name:"main";
657 }
658
659 void
660 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
661
662         if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))
663                 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
664
665         if(thread_return){
666
667                 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
668                         THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
669         }
670
671         CloseHandle(thread->handle);
672         free(thread->name);
673         free(thread);
674 }
675
676 void xbt_os_thread_exit(int *retval) {
677    if(retval)
678         ExitThread(*retval);
679    else
680         ExitThread(0);
681 }
682
683 xbt_os_thread_t xbt_os_thread_self(void) {
684    return TlsGetValue(xbt_self_thread_key);
685 }
686
687 void *xbt_os_thread_getparam(void) {
688    xbt_os_thread_t t = xbt_os_thread_self();
689    return t->param;
690 }
691
692
693 void xbt_os_thread_yield(void) {
694     Sleep(0);
695 }
696 void xbt_os_thread_cancel(xbt_os_thread_t t) {
697    THROW_UNIMPLEMENTED;
698 }
699
700 /****** mutex related functions ******/
701 typedef struct xbt_os_mutex_ {
702   /* KEEP IT IN SYNC WITH xbt_thread.c */
703    CRITICAL_SECTION lock;
704 } s_xbt_os_mutex_t;
705
706 xbt_os_mutex_t xbt_os_mutex_init(void) {
707    xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
708
709    /* initialize the critical section object */
710    InitializeCriticalSection(&(res->lock));
711
712    return res;
713 }
714
715 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) {
716
717    EnterCriticalSection(& mutex->lock);
718 }
719
720 void xbt_os_mutex_tryacquire(xbt_os_mutex_t mutex)
721 {
722         TryEnterCriticalSection(&mutex->lock);
723 }
724
725 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay) {
726         THROW_UNIMPLEMENTED;
727 }
728
729 void xbt_os_mutex_release(xbt_os_mutex_t mutex) {
730
731    LeaveCriticalSection (&mutex->lock);
732
733 }
734
735 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
736
737    if (!mutex) return;
738
739    DeleteCriticalSection(& mutex->lock);
740    free(mutex);
741 }
742
743 /***** condition related functions *****/
744  enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
745     SIGNAL = 0,
746     BROADCAST = 1,
747     MAX_EVENTS = 2
748  };
749
750 typedef struct xbt_os_cond_ {
751   /* KEEP IT IN SYNC WITH xbt_thread.c */
752    HANDLE events[MAX_EVENTS];
753
754    unsigned int waiters_count;           /* the number of waiters                        */
755    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
756 } s_xbt_os_cond_t;
757
758 xbt_os_cond_t xbt_os_cond_init(void) {
759
760    xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1);
761
762    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
763
764    /* initialize the critical section object */
765    InitializeCriticalSection(& res->waiters_count_lock);
766
767    res->waiters_count = 0;
768
769    /* Create an auto-reset event */
770    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL);
771
772    if(!res->events[SIGNAL]){
773       DeleteCriticalSection(& res->waiters_count_lock);
774       free(res);
775       THROW0(system_error,0,"CreateEvent failed for the signals");
776    }
777
778    /* Create a manual-reset event. */
779    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
780
781    if(!res->events[BROADCAST]){
782
783       DeleteCriticalSection(& res->waiters_count_lock);
784       CloseHandle(res->events[SIGNAL]);
785       free(res);
786       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
787    }
788
789    return res;
790 }
791
792 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
793
794    unsigned long wait_result;
795    int is_last_waiter;
796
797    /* lock the threads counter and increment it */
798    EnterCriticalSection (& cond->waiters_count_lock);
799    cond->waiters_count++;
800    LeaveCriticalSection (& cond->waiters_count_lock);
801
802    /* unlock the mutex associate with the condition */
803    LeaveCriticalSection (& mutex->lock);
804
805    /* wait for a signal (broadcast or no) */
806    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
807
808    if(wait_result == WAIT_FAILED)
809      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
810
811    /* we have a signal lock the condition */
812    EnterCriticalSection (& cond->waiters_count_lock);
813    cond->waiters_count--;
814
815    /* it's the last waiter or it's a broadcast ? */
816    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
817
818    LeaveCriticalSection (& cond->waiters_count_lock);
819
820    /* yes it's the last waiter or it's a broadcast
821     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
822     * by the system.
823     */
824    if (is_last_waiter)
825       if(!ResetEvent (cond->events[BROADCAST]))
826         THROW0(system_error,0,"ResetEvent failed");
827
828    /* relock the mutex associated with the condition in accordance with the posix thread specification */
829    EnterCriticalSection (& mutex->lock);
830 }
831 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
832
833    unsigned long wait_result = WAIT_TIMEOUT;
834    int is_last_waiter;
835    unsigned long end = (unsigned long)(delay * 1000);
836
837
838    if (delay < 0) {
839       xbt_os_cond_wait(cond,mutex);
840    } else {
841           DEBUG3("xbt_cond_timedwait(%p,%p,%ul)",&(cond->events),&(mutex->lock),end);
842
843    /* lock the threads counter and increment it */
844    EnterCriticalSection (& cond->waiters_count_lock);
845    cond->waiters_count++;
846    LeaveCriticalSection (& cond->waiters_count_lock);
847
848    /* unlock the mutex associate with the condition */
849    LeaveCriticalSection (& mutex->lock);
850    /* wait for a signal (broadcast or no) */
851
852    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, end);
853
854    switch(wait_result) {
855      case WAIT_TIMEOUT:
856         THROW3(timeout_error,GetLastError(),"condition %p (mutex %p) wasn't signaled before timeout (%f)",cond,mutex, delay);
857         case WAIT_FAILED:
858      THROW0(system_error,GetLastError(),"WaitForMultipleObjects failed, so we cannot wait on the condition");
859    }
860
861    /* we have a signal lock the condition */
862    EnterCriticalSection (& cond->waiters_count_lock);
863    cond->waiters_count--;
864
865    /* it's the last waiter or it's a broadcast ? */
866    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
867
868    LeaveCriticalSection (& cond->waiters_count_lock);
869
870    /* yes it's the last waiter or it's a broadcast
871     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
872     * by the system.
873     */
874    if (is_last_waiter)
875       if(!ResetEvent (cond->events[BROADCAST]))
876         THROW0(system_error,0,"ResetEvent failed");
877
878    /* relock the mutex associated with the condition in accordance with the posix thread specification */
879    EnterCriticalSection (& mutex->lock);
880    }
881         /*THROW_UNIMPLEMENTED;*/
882 }
883
884 void xbt_os_cond_signal(xbt_os_cond_t cond) {
885    int have_waiters;
886
887    EnterCriticalSection (& cond->waiters_count_lock);
888    have_waiters = cond->waiters_count > 0;
889    LeaveCriticalSection (& cond->waiters_count_lock);
890
891    if (have_waiters)
892      if(!SetEvent(cond->events[SIGNAL]))
893        THROW0(system_error,0,"SetEvent failed");
894
895    xbt_os_thread_yield();
896 }
897
898 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
899    int have_waiters;
900
901    EnterCriticalSection (& cond->waiters_count_lock);
902    have_waiters = cond->waiters_count > 0;
903    LeaveCriticalSection (& cond->waiters_count_lock);
904
905    if (have_waiters)
906      SetEvent(cond->events[BROADCAST]);
907 }
908
909 void xbt_os_cond_destroy(xbt_os_cond_t cond){
910    int error = 0;
911
912    if (!cond) return;
913
914    if(!CloseHandle(cond->events[SIGNAL]))
915      error = 1;
916
917    if(!CloseHandle(cond->events[BROADCAST]))
918      error = 1;
919
920    DeleteCriticalSection(& cond->waiters_count_lock);
921
922    xbt_free(cond);
923
924    if (error)
925      THROW0(system_error,0,"Error while destroying the condition");
926 }
927
928 typedef struct xbt_os_sem_ {
929    HANDLE h;
930    unsigned int value;
931    CRITICAL_SECTION value_lock;  /* protect access to value of the semaphore  */
932 }s_xbt_os_sem_t ;
933
934 xbt_os_sem_t
935 xbt_os_sem_init(unsigned int value)
936 {
937         xbt_os_sem_t res;
938
939         if(value > INT_MAX)
940         THROW1(arg_error,value,"Semaphore initial value too big: %ud cannot be stored as a signed int",value);
941
942         res = (xbt_os_sem_t)xbt_new0(s_xbt_os_sem_t,1);
943
944         if(!(res->h = CreateSemaphore(NULL,value,(long)INT_MAX,NULL))) {
945                 THROW1(system_error,GetLastError(),"CreateSemaphore() failed: %s",
946             strerror(GetLastError()));
947             return NULL;
948         }
949
950         res->value = value;
951
952         InitializeCriticalSection(&(res->value_lock));
953
954         return res;
955 }
956
957 void
958 xbt_os_sem_acquire(xbt_os_sem_t sem)
959 {
960         if(!sem)
961                 THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore");
962
963         /* wait failure */
964         if(WAIT_OBJECT_0 != WaitForSingleObject(sem->h,INFINITE))
965                 THROW1(system_error,GetLastError(),"WaitForSingleObject() failed: %s",
966                 strerror(GetLastError()));
967         EnterCriticalSection(&(sem->value_lock));
968         sem->value--;
969         LeaveCriticalSection(&(sem->value_lock));
970 }
971
972 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
973 {
974         long seconds;
975         long milliseconds;
976         double end = timeout + xbt_os_time();
977
978         if(!sem)
979                 THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore");
980
981         if (timeout < 0)
982         {
983                 xbt_os_sem_acquire(sem);
984         }
985         else /* timeout can be zero <-> try acquire ) */
986         {
987
988                 seconds = (long) floor(end);
989                 milliseconds = (long)( ( end - seconds) * 1000);
990                 milliseconds += (seconds * 1000);
991
992                 switch(WaitForSingleObject(sem->h,milliseconds))
993                 {
994                         case WAIT_OBJECT_0:
995                         EnterCriticalSection(&(sem->value_lock));
996                         sem->value--;
997                         LeaveCriticalSection(&(sem->value_lock));
998                         return;
999
1000                         case WAIT_TIMEOUT:
1001                         THROW2(timeout_error,GetLastError(),"semaphore %p wasn't signaled before timeout (%f)",sem,timeout);
1002                         return;
1003
1004                         default:
1005                         THROW3(system_error,GetLastError(),"WaitForSingleObject(%p,%f) failed: %s",sem,timeout, strerror(GetLastError()));
1006                 }
1007         }
1008 }
1009
1010 void
1011 xbt_os_sem_release(xbt_os_sem_t sem)
1012 {
1013         if(!sem)
1014                 THROW0(arg_error,EINVAL,"Cannot release the NULL semaphore");
1015
1016         if(!ReleaseSemaphore(sem->h,1, NULL))
1017                 THROW1(system_error,GetLastError(),"ReleaseSemaphore() failed: %s",
1018                 strerror(GetLastError()));
1019         EnterCriticalSection (&(sem->value_lock));
1020         sem->value++;
1021         LeaveCriticalSection(&(sem->value_lock));
1022 }
1023
1024 void
1025 xbt_os_sem_destroy(xbt_os_sem_t sem)
1026 {
1027         if(!sem)
1028                 THROW0(arg_error,EINVAL,"Cannot destroy the NULL semaphore");
1029
1030         if(!CloseHandle(sem->h))
1031                 THROW1(system_error,GetLastError(),"CloseHandle() failed: %s",
1032                 strerror(GetLastError()));
1033
1034          DeleteCriticalSection(&(sem->value_lock));
1035
1036          xbt_free(sem);
1037
1038 }
1039
1040 void
1041 xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue)
1042 {
1043         if(!sem)
1044                 THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore");
1045
1046         EnterCriticalSection(&(sem->value_lock));
1047         *svalue = sem->value;
1048         LeaveCriticalSection(&(sem->value_lock));
1049 }
1050
1051 #endif