Logo AND Algorithmique Numérique Distribuée

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