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 */
7 /* Copyright 2006,2007 Malek Cherier, Martin Quinson
8 * All right reserved. */
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. */
13 #include "xbt/sysdep.h"
15 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
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 */
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os,xbt,"Synchronization mechanism (OS-level)");
23 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
26 #include <semaphore.h>
28 /* use named sempahore instead */
30 # define MAX_SEM_NAME ((size_t)13)
31 static int __next_sem_ID = 0;
32 static pthread_mutex_t __next_sem_ID_lock;
35 typedef struct xbt_os_thread_ {
39 pvoid_f_pvoid_t start_routine;
42 static xbt_os_thread_t main_thread = NULL;
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;
48 /* frees the xbt_os_thread_t corresponding to the current thread */
49 static void xbt_os_thread_free_thread_data(void*d){
53 /* callback: context fetching */
54 static ex_ctx_t *_os_thread_ex_ctx(void) {
55 return xbt_os_thread_self()->exception;
58 /* callback: termination */
59 static void _os_thread_ex_terminate(xbt_ex_t * e) {
63 /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
66 void xbt_os_thread_mod_init(void) {
69 if (thread_mod_inited)
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");
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);
82 __xbt_ex_ctx = _os_thread_ex_ctx;
83 __xbt_ex_terminate = _os_thread_ex_terminate;
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
90 if ((errcode = pthread_mutex_init(&__next_sem_ID_lock,NULL)))
91 THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",strerror(errcode));
95 thread_mod_inited = 1;
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 */
102 // if ((errcode=pthread_key_delete(xbt_self_thread_key)))
103 // THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
106 static void * wrapper_start_routine(void *s) {
107 xbt_os_thread_t t = s;
110 if ((errcode=pthread_setspecific(xbt_self_thread_key,t)))
111 THROW0(system_error,errcode,
112 "pthread_setspecific failed for xbt_self_thread_key");
114 return (*(t->start_routine))(t->param);
117 xbt_os_thread_t xbt_os_thread_create(const char*name,
118 pvoid_f_pvoid_t start_routine,
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);
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));
137 const char* xbt_os_thread_name(xbt_os_thread_t t) {
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";
146 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
150 if ((errcode = pthread_join(thread->t,thread_return)))
151 THROW1(system_error,errcode, "pthread_join failed: %s",
153 if (thread->exception)
154 free(thread->exception);
156 if (thread == main_thread) /* just killed main thread */
162 void xbt_os_thread_exit(int *retval) {
163 pthread_exit(retval);
166 xbt_os_thread_t xbt_os_thread_self(void) {
169 if (!thread_mod_inited)
172 res = pthread_getspecific(xbt_self_thread_key);
180 void xbt_os_thread_yield(void) {
183 void xbt_os_thread_cancel(xbt_os_thread_t t) {
184 pthread_cancel(t->t);
186 /****** mutex related functions ******/
187 typedef struct xbt_os_mutex_ {
188 /* KEEP IT IN SYNC WITH xbt_thread.c */
195 xbt_os_mutex_t xbt_os_mutex_init(void) {
196 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
199 if ((errcode = pthread_mutex_init(&(res->m),NULL)))
200 THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",
206 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) {
209 if ((errcode=pthread_mutex_lock(&(mutex->m))))
210 THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s",
211 mutex, strerror(errcode));
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
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)
224 long ellapsed_time = 0;
229 /* the mutex could not be acquired because it was already locked by an other thread */
230 rv = pthread_mutex_trylock(mutex);
233 ts.tv_nsec = 2.5e7 /* (25 ms (2 context switch + 5 ms)) */;
238 }while(EINTR == errno);
240 ellapsed_time += ts.tv_nsec;
243 while (/* locked */ (EBUSY == rv) && /* !timeout */ (ellapsed_time < ((long)(abs_timeout->tv_sec * 1e9) + abs_timeout->tv_nsec)));
245 return (EBUSY == rv) ? ETIMEDOUT : rv;
250 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay) {
252 struct timespec ts_end;
253 double end = delay + xbt_os_time();
256 xbt_os_mutex_acquire(mutex);
258 else if(!delay /* equals 0 */)
260 if ((errcode=pthread_mutex_trylock(&(mutex->m))))
261 THROW2(system_error,errcode,"pthread_mutex_trylock(%p) failed: %s",mutex, strerror(errcode));
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);
268 switch ((errcode=pthread_mutex_timedlock(&(mutex->m),&ts_end)))
274 THROW2(timeout_error,errcode,"mutex %p wasn't signaled before timeout (%f)",mutex,delay);
277 THROW3(system_error,errcode,"pthread_mutex_timedlock(%p,%f) failed: %s",mutex,delay, strerror(errcode));
282 void xbt_os_mutex_release(xbt_os_mutex_t mutex) {
285 if ((errcode=pthread_mutex_unlock(&(mutex->m))))
286 THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s",
287 mutex, strerror(errcode));
290 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
295 if ((errcode=pthread_mutex_destroy(&(mutex->m))))
296 THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s",
297 mutex, strerror(errcode));
301 /***** condition related functions *****/
302 typedef struct xbt_os_cond_ {
303 /* KEEP IT IN SYNC WITH xbt_thread.c */
307 xbt_os_cond_t xbt_os_cond_init(void) {
308 xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t,1);
310 if ((errcode=pthread_cond_init(&(res->c),NULL)))
311 THROW1(system_error,errcode,"pthread_cond_init() failed: %s",
317 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
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));
325 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
327 struct timespec ts_end;
328 double end = delay + xbt_os_time();
331 xbt_os_cond_wait(cond,mutex);
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)) ) {
340 THROW3(timeout_error,errcode,"condition %p (mutex %p) wasn't signaled before timeout (%f)",
343 THROW4(system_error,errcode,"pthread_cond_timedwait(%p,%p,%f) failed: %s",
344 cond,mutex, delay, strerror(errcode));
349 void xbt_os_cond_signal(xbt_os_cond_t cond) {
351 if ((errcode=pthread_cond_signal(&(cond->c))))
352 THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s",
353 cond, strerror(errcode));
356 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
358 if ((errcode=pthread_cond_broadcast(&(cond->c))))
359 THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s",
360 cond, strerror(errcode));
362 void xbt_os_cond_destroy(xbt_os_cond_t cond){
367 if ((errcode=pthread_cond_destroy(&(cond->c))))
368 THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s",
369 cond, strerror(errcode));
373 void *xbt_os_thread_getparam(void) {
374 xbt_os_thread_t t = xbt_os_thread_self();
375 return t?t->param:NULL;
378 typedef struct xbt_os_sem_ {
379 #ifndef HAVE_SEM_WAIT
388 xbt_os_sem_init(unsigned int value)
390 xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t,1);
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()
397 #ifndef HAVE_SEM_INIT
398 res->name = (char*) calloc(MAX_SEM_NAME + 1,sizeof(char));
400 if((errcode = pthread_mutex_lock(&__next_sem_ID_lock)))
401 THROW1(system_error,errcode,"pthread_mutex_lock() failed: %s", strerror(errcode));
405 if((errcode = pthread_mutex_unlock(&__next_sem_ID_lock)))
406 THROW1(system_error,errcode,"pthread_mutex_unlock() failed: %s", strerror(errcode));
408 sprintf(res->name,"/%d.%d",(*xbt_getpid)(),__next_sem_ID);
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));
413 if(sem_unlink(res->name) < 0)
414 THROW1(system_error,errno,"sem_unlink() failed: %s", strerror(errno));
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",
428 xbt_os_sem_acquire(xbt_os_sem_t 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",
437 if(sem_wait(&(sem->s)) < 0)
438 THROW1(system_error,errno,"sem_wait() failed: %s",
443 #ifndef HAVE_SEM_TIMEDWAIT
444 /* if the function is not availabled or if is MAC OS X use sem_trywait() to define
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)
451 long ellapsed_time = 0;
456 rv = sem_trywait(sem);
458 ts.tv_nsec = 2.5e7 /* (25 ms (2 * context switch + 5 ms)) */;
463 }while(EINTR == errno);
465 ellapsed_time += ts.tv_nsec;
468 while(/* locked */ (EAGAIN == rv) && /* !timeout */ ellapsed_time < ((long)(abs_timeout->tv_sec * 1e9) + abs_timeout->tv_nsec));
470 return (EAGAIN == rv) ? ETIMEDOUT : rv;
475 void xbt_os_sem_timedacquire(xbt_os_sem_t sem,double timeout)
478 struct timespec ts_end;
479 double end = timeout + xbt_os_time();
482 THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore");
486 xbt_os_sem_acquire(sem);
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));
494 if(sem_trywait(sem->s) < 0)
495 THROW2(system_error,errno,"sem_trywait(%p) failed: %s",sem,strerror(errno));
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);
504 #ifndef HAVE_SEM_WAIT
505 switch ((errcode = sem_timedwait(sem->s,&ts_end)))
507 switch ((errcode = sem_timedwait(&(sem->s),&ts_end)))
514 THROW2(timeout_error,errcode,"semaphore %p wasn't signaled before timeout (%f)",sem,timeout);
517 THROW3(system_error,errcode,"sem_timedwait(%p,%f) failed: %s",sem,timeout, strerror(errcode));
524 xbt_os_sem_release(xbt_os_sem_t sem)
527 THROW0(arg_error,EINVAL,"Cannot release of the NULL semaphore");
529 #ifndef HAVE_SEM_WAIT
530 if(sem_post((sem->s)) < 0)
531 THROW1(system_error,errno,"sem_post() failed: %s",
534 if(sem_post(&(sem->s)) < 0)
535 THROW1(system_error,errno,"sem_post() failed: %s",
541 xbt_os_sem_destroy(xbt_os_sem_t sem)
544 THROW0(arg_error,EINVAL,"Cannot destroy the NULL sempahore");
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)
550 if(sem_close((sem->s)) < 0)
551 THROW1(system_error,errno,"sem_close() failed: %s",
557 if(sem_destroy(&(sem->s)) < 0)
558 THROW1(system_error,errno,"sem_destroy() failed: %s",
566 xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue)
569 THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore");
571 #ifndef HAVE_SEM_WAIT
572 if(sem_getvalue((sem->s),svalue) < 0)
573 THROW1(system_error,errno,"sem_getvalue() failed: %s",
576 if(sem_getvalue(&(sem->s),svalue) < 0)
577 THROW1(system_error,errno,"sem_getvalue() failed: %s",
582 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
588 typedef struct xbt_os_thread_ {
590 HANDLE handle; /* the win thread handle */
591 unsigned long id; /* the win thread id */
592 pvoid_f_pvoid_t start_routine;
594 } s_xbt_os_thread_t ;
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
601 /* the default size of the stack of the threads (in bytes)*/
602 #define XBT_DEFAULT_THREAD_STACK_SIZE 4096
604 /* key to the TLS containing the xbt_os_thread_t structure */
605 static unsigned long xbt_self_thread_key;
607 void xbt_os_thread_mod_init(void) {
608 xbt_self_thread_key = TlsAlloc();
610 void xbt_os_thread_mod_exit(void) {
612 if (!TlsFree(xbt_self_thread_key))
613 THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
616 static DWORD WINAPI wrapper_start_routine(void *s) {
617 xbt_os_thread_t t = (xbt_os_thread_t)s;
620 if(!TlsSetValue(xbt_self_thread_key,t))
621 THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
623 rv = (*(t->start_routine))(t->param);
625 return *((DWORD*)rv);
629 xbt_os_thread_t xbt_os_thread_create(const char *name,pvoid_f_pvoid_t start_routine,
632 xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1);
634 t->name = xbt_strdup(name);
635 t->start_routine = start_routine ;
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));
644 THROW0(system_error,(int)GetLastError(),"CreateThread failed");
650 const char* xbt_os_thread_name(xbt_os_thread_t t) {
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";
660 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
662 if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))
663 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
667 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
668 THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
671 CloseHandle(thread->handle);
676 void xbt_os_thread_exit(int *retval) {
683 xbt_os_thread_t xbt_os_thread_self(void) {
684 return TlsGetValue(xbt_self_thread_key);
687 void *xbt_os_thread_getparam(void) {
688 xbt_os_thread_t t = xbt_os_thread_self();
693 void xbt_os_thread_yield(void) {
696 void xbt_os_thread_cancel(xbt_os_thread_t t) {
700 /****** mutex related functions ******/
701 typedef struct xbt_os_mutex_ {
702 /* KEEP IT IN SYNC WITH xbt_thread.c */
703 CRITICAL_SECTION lock;
706 xbt_os_mutex_t xbt_os_mutex_init(void) {
707 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
709 /* initialize the critical section object */
710 InitializeCriticalSection(&(res->lock));
715 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) {
717 EnterCriticalSection(& mutex->lock);
720 void xbt_os_mutex_tryacquire(xbt_os_mutex_t mutex)
722 TryEnterCriticalSection(&mutex->lock);
725 void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay) {
729 void xbt_os_mutex_release(xbt_os_mutex_t mutex) {
731 LeaveCriticalSection (&mutex->lock);
735 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
739 DeleteCriticalSection(& mutex->lock);
743 /***** condition related functions *****/
744 enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
750 typedef struct xbt_os_cond_ {
751 /* KEEP IT IN SYNC WITH xbt_thread.c */
752 HANDLE events[MAX_EVENTS];
754 unsigned int waiters_count; /* the number of waiters */
755 CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */
758 xbt_os_cond_t xbt_os_cond_init(void) {
760 xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1);
762 memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
764 /* initialize the critical section object */
765 InitializeCriticalSection(& res->waiters_count_lock);
767 res->waiters_count = 0;
769 /* Create an auto-reset event */
770 res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL);
772 if(!res->events[SIGNAL]){
773 DeleteCriticalSection(& res->waiters_count_lock);
775 THROW0(system_error,0,"CreateEvent failed for the signals");
778 /* Create a manual-reset event. */
779 res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
781 if(!res->events[BROADCAST]){
783 DeleteCriticalSection(& res->waiters_count_lock);
784 CloseHandle(res->events[SIGNAL]);
786 THROW0(system_error,0,"CreateEvent failed for the broadcasts");
792 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
794 unsigned long wait_result;
797 /* lock the threads counter and increment it */
798 EnterCriticalSection (& cond->waiters_count_lock);
799 cond->waiters_count++;
800 LeaveCriticalSection (& cond->waiters_count_lock);
802 /* unlock the mutex associate with the condition */
803 LeaveCriticalSection (& mutex->lock);
805 /* wait for a signal (broadcast or no) */
806 wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
808 if(wait_result == WAIT_FAILED)
809 THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
811 /* we have a signal lock the condition */
812 EnterCriticalSection (& cond->waiters_count_lock);
813 cond->waiters_count--;
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));
818 LeaveCriticalSection (& cond->waiters_count_lock);
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
825 if(!ResetEvent (cond->events[BROADCAST]))
826 THROW0(system_error,0,"ResetEvent failed");
828 /* relock the mutex associated with the condition in accordance with the posix thread specification */
829 EnterCriticalSection (& mutex->lock);
831 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
833 unsigned long wait_result = WAIT_TIMEOUT;
835 unsigned long end = (unsigned long)(delay * 1000);
839 xbt_os_cond_wait(cond,mutex);
841 DEBUG3("xbt_cond_timedwait(%p,%p,%ul)",&(cond->events),&(mutex->lock),end);
843 /* lock the threads counter and increment it */
844 EnterCriticalSection (& cond->waiters_count_lock);
845 cond->waiters_count++;
846 LeaveCriticalSection (& cond->waiters_count_lock);
848 /* unlock the mutex associate with the condition */
849 LeaveCriticalSection (& mutex->lock);
850 /* wait for a signal (broadcast or no) */
852 wait_result = WaitForMultipleObjects (2, cond->events, FALSE, end);
854 switch(wait_result) {
856 THROW3(timeout_error,GetLastError(),"condition %p (mutex %p) wasn't signaled before timeout (%f)",cond,mutex, delay);
858 THROW0(system_error,GetLastError(),"WaitForMultipleObjects failed, so we cannot wait on the condition");
861 /* we have a signal lock the condition */
862 EnterCriticalSection (& cond->waiters_count_lock);
863 cond->waiters_count--;
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));
868 LeaveCriticalSection (& cond->waiters_count_lock);
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
875 if(!ResetEvent (cond->events[BROADCAST]))
876 THROW0(system_error,0,"ResetEvent failed");
878 /* relock the mutex associated with the condition in accordance with the posix thread specification */
879 EnterCriticalSection (& mutex->lock);
881 /*THROW_UNIMPLEMENTED;*/
884 void xbt_os_cond_signal(xbt_os_cond_t cond) {
887 EnterCriticalSection (& cond->waiters_count_lock);
888 have_waiters = cond->waiters_count > 0;
889 LeaveCriticalSection (& cond->waiters_count_lock);
892 if(!SetEvent(cond->events[SIGNAL]))
893 THROW0(system_error,0,"SetEvent failed");
895 xbt_os_thread_yield();
898 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
901 EnterCriticalSection (& cond->waiters_count_lock);
902 have_waiters = cond->waiters_count > 0;
903 LeaveCriticalSection (& cond->waiters_count_lock);
906 SetEvent(cond->events[BROADCAST]);
909 void xbt_os_cond_destroy(xbt_os_cond_t cond){
914 if(!CloseHandle(cond->events[SIGNAL]))
917 if(!CloseHandle(cond->events[BROADCAST]))
920 DeleteCriticalSection(& cond->waiters_count_lock);
925 THROW0(system_error,0,"Error while destroying the condition");
928 typedef struct xbt_os_sem_ {
931 CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */
935 xbt_os_sem_init(unsigned int value)
940 THROW1(arg_error,value,"Semaphore initial value too big: %ud cannot be stored as a signed int",value);
942 res = (xbt_os_sem_t)xbt_new0(s_xbt_os_sem_t,1);
944 if(!(res->h = CreateSemaphore(NULL,value,(long)INT_MAX,NULL))) {
945 THROW1(system_error,GetLastError(),"CreateSemaphore() failed: %s",
946 strerror(GetLastError()));
952 InitializeCriticalSection(&(res->value_lock));
958 xbt_os_sem_acquire(xbt_os_sem_t sem)
961 THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore");
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));
969 LeaveCriticalSection(&(sem->value_lock));
972 void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout)
976 double end = timeout + xbt_os_time();
979 THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore");
983 xbt_os_sem_acquire(sem);
985 else /* timeout can be zero <-> try acquire ) */
988 seconds = (long) floor(end);
989 milliseconds = (long)( ( end - seconds) * 1000);
990 milliseconds += (seconds * 1000);
992 switch(WaitForSingleObject(sem->h,milliseconds))
995 EnterCriticalSection(&(sem->value_lock));
997 LeaveCriticalSection(&(sem->value_lock));
1001 THROW2(timeout_error,GetLastError(),"semaphore %p wasn't signaled before timeout (%f)",sem,timeout);
1005 THROW3(system_error,GetLastError(),"WaitForSingleObject(%p,%f) failed: %s",sem,timeout, strerror(GetLastError()));
1011 xbt_os_sem_release(xbt_os_sem_t sem)
1014 THROW0(arg_error,EINVAL,"Cannot release the NULL semaphore");
1016 if(!ReleaseSemaphore(sem->h,1, NULL))
1017 THROW1(system_error,GetLastError(),"ReleaseSemaphore() failed: %s",
1018 strerror(GetLastError()));
1019 EnterCriticalSection (&(sem->value_lock));
1021 LeaveCriticalSection(&(sem->value_lock));
1025 xbt_os_sem_destroy(xbt_os_sem_t sem)
1028 THROW0(arg_error,EINVAL,"Cannot destroy the NULL semaphore");
1030 if(!CloseHandle(sem->h))
1031 THROW1(system_error,GetLastError(),"CloseHandle() failed: %s",
1032 strerror(GetLastError()));
1034 DeleteCriticalSection(&(sem->value_lock));
1041 xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue)
1044 THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore");
1046 EnterCriticalSection(&(sem->value_lock));
1047 *svalue = sem->value;
1048 LeaveCriticalSection(&(sem->value_lock));