Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
I'm a testing freak, I know
[simgrid.git] / src / xbt / xbt_thread.c
1 /* $Id$ */
2
3 /* xbt_thread -- portability layer over the pthread API                     */
4
5 /* Copyright 2006,2007 Malek Cherier, Martin Quinson          
6  * All right reserved.                                                      */
7
8 /* This program is free software; you can redistribute it and/or modify it
9  * under the terms of the license (GNU LGPL) which comes with this package. */
10
11 #include "xbt/sysdep.h"
12 #include "xbt/ex.h"
13 #include "portable.h"
14 #include "xbt/xbt_thread.h" /* This module */
15 #include "xbt_modinter.h" /* Initialization/finalization of this module */
16
17
18
19 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
20 #ifdef HAVE_PTHREAD_H
21 #include <pthread.h>
22
23 typedef struct xbt_thread_ {
24    pthread_t t;
25    void *param;
26    pvoid_f_pvoid_t *start_routine;
27 } s_xbt_thread_t ;
28
29 /* thread-specific data containing the xbt_thread_t structure */
30 static pthread_key_t xbt_self_thread_key;
31
32 /* frees the xbt_thread_t corresponding to the current thread */
33 static void xbt_thread_free_thread_data(void*d){
34    free(d);
35 }
36
37 void xbt_thread_mod_init(void) {
38    int errcode;
39    
40    if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL)))
41      THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key");
42 }
43 void xbt_thread_mod_exit(void) {
44    /* FIXME: don't try to free our key on shutdown. Valgrind detects no leak if we don't, and whine if we try to */
45 //   int errcode;
46    
47 //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
48 //     THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
49 }
50
51 static void * wrapper_start_routine(void *s) {
52   xbt_thread_t t = s;   
53   int errcode;
54
55   if ((errcode=pthread_setspecific(xbt_self_thread_key,t)))
56     THROW0(system_error,errcode,"pthread_setspecific failed for xbt_self_thread_key");   
57   return t->start_routine(t->param);
58 }
59
60 xbt_thread_t xbt_thread_create(pvoid_f_pvoid_t start_routine,
61                                void* param)  {
62    int errcode;
63
64    xbt_thread_t res_thread=xbt_new(s_xbt_thread_t,1);
65    res_thread->start_routine = start_routine;
66    res_thread->param = param;
67
68    
69    if ((errcode = pthread_create(&(res_thread->t), NULL, wrapper_start_routine, res_thread)))
70      THROW0(system_error,errcode, "pthread_create failed");
71
72    return res_thread;
73 }
74
75 void 
76 xbt_thread_join(xbt_thread_t thread,void ** thread_return) {
77         
78         int errcode;   
79         
80         if ((errcode = pthread_join(thread->t,thread_return)))
81                 THROW0(system_error,errcode, "pthread_join failed");
82         free(thread);   
83 }                      
84
85 void xbt_thread_exit(int *retval) {
86    pthread_exit(retval);
87 }
88
89 xbt_thread_t xbt_thread_self(void) {
90    return pthread_getspecific(xbt_self_thread_key);
91 }
92
93 #include <sched.h>
94 void xbt_thread_yield(void) {
95    sched_yield();
96 }
97 /****** mutex related functions ******/
98 typedef struct xbt_mutex_ {
99    pthread_mutex_t m;
100 } s_xbt_mutex_t;
101
102 xbt_mutex_t xbt_mutex_init(void) {
103    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
104    int errcode;
105    
106    if ((errcode = pthread_mutex_init(&(res->m),NULL)))
107      THROW0(system_error,errcode,"pthread_mutex_init() failed");
108    
109    return res;
110 }
111
112 void xbt_mutex_lock(xbt_mutex_t mutex) {
113    int errcode;
114    
115    if ((errcode=pthread_mutex_lock(&(mutex->m))))
116      THROW1(system_error,errcode,"pthread_mutex_lock(%p) failed",mutex);
117 }
118
119 void xbt_mutex_unlock(xbt_mutex_t mutex) {
120    int errcode;
121    
122    if ((errcode=pthread_mutex_unlock(&(mutex->m))))
123      THROW1(system_error,errcode,"pthread_mutex_unlock(%p) failed",mutex);
124 }
125
126 void xbt_mutex_destroy(xbt_mutex_t mutex) {
127    int errcode;
128    
129    if (!mutex) return;
130    
131    if ((errcode=pthread_mutex_destroy(&(mutex->m))))
132      THROW1(system_error,errcode,"pthread_mutex_destroy(%p) failed",mutex);
133    free(mutex);
134 }
135
136 /***** condition related functions *****/
137 typedef struct xbt_thcond_ {
138    pthread_cond_t c;
139 } s_xbt_thcond_t;
140
141 xbt_thcond_t xbt_thcond_init(void) {
142    xbt_thcond_t res = xbt_new(s_xbt_thcond_t,1);
143    int errcode;
144    if ((errcode=pthread_cond_init(&(res->c),NULL)))
145      THROW0(system_error,errcode,"pthread_cond_init() failed");
146
147    return res;
148 }
149
150 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
151    int errcode;
152    if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m))))
153      THROW2(system_error,errcode,"pthread_cond_wait(%p,%p) failed",cond,mutex);
154 }
155
156 void xbt_thcond_signal(xbt_thcond_t cond) {
157    int errcode;
158    if ((errcode=pthread_cond_signal(&(cond->c))))
159      THROW1(system_error,errcode,"pthread_cond_signal(%p) failed",cond);
160 }
161          
162 void xbt_thcond_broadcast(xbt_thcond_t cond){
163    int errcode;
164    if ((errcode=pthread_cond_broadcast(&(cond->c))))
165      THROW1(system_error,errcode,"pthread_cond_broadcast(%p) failed",cond);
166 }
167 void xbt_thcond_destroy(xbt_thcond_t cond){
168    int errcode;
169
170    if (!cond) return;
171
172    if ((errcode=pthread_cond_destroy(&(cond->c))))
173      THROW1(system_error,errcode,"pthread_cond_destroy(%p) failed",cond);
174    free(cond);
175 }
176
177 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
178
179 #elif defined(WIN32)
180
181 typedef struct xbt_thread_ {
182   HANDLE handle;                  /* the win thread handle        */
183   unsigned long id;               /* the win thread id            */
184   pvoid_f_pvoid_t *start_routine;
185   void* param;
186 } s_xbt_thread_t ;
187
188 /* key to the TLS containing the xbt_thread_t structure */
189 static unsigned long xbt_self_thread_key;
190
191 void xbt_thread_mod_init(void) {
192    xbt_self_thread_key = TlsAlloc();
193 }
194 void xbt_thread_mod_exit(void) {
195    
196    if (!TlsFree(xbt_self_thread_key)) 
197      THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
198 }
199
200 static DWORD WINAPI  wrapper_start_routine(void *s) {
201   xbt_thread_t t = (xbt_thread_t)s;
202  
203     if(!TlsSetValue(xbt_self_thread_key,t))
204      THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
205    
206    return (DWORD)t->start_routine(t->param);
207 }
208
209
210 xbt_thread_t xbt_thread_create(pvoid_f_pvoid_t start_routine,
211                                void* param)  {
212    
213    xbt_thread_t t = xbt_new(s_xbt_thread_t,1);
214
215    t->start_routine = start_routine ;
216    t->param = param;
217    
218    t->handle = CreateThread(NULL,0,
219                             (LPTHREAD_START_ROUTINE)wrapper_start_routine,
220                             t,0,&(t->id));
221         
222    if(!t->handle) {
223      xbt_free(t);
224      THROW0(system_error,(int)GetLastError(),"CreateThread failed");
225    }
226    
227    return t;
228 }
229
230 void 
231 xbt_thread_join(xbt_thread_t thread,void ** thread_return) {
232
233         if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))  
234                 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
235                 
236         if(thread_return){
237                 
238                 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
239                         THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
240         }
241         
242         CloseHandle(thread->handle);
243         free(thread);
244 }
245
246 void xbt_thread_exit(int *retval) {
247    if(retval)
248         ExitThread(*retval);
249    else
250         ExitThread(0);
251 }
252
253 xbt_thread_t xbt_thread_self(void) {
254    return TlsGetValue(xbt_self_thread_key);
255 }
256
257 void xbt_thread_yield(void) {
258     Sleep(0);
259 }
260
261 /****** mutex related functions ******/
262 typedef struct xbt_mutex_ {
263    CRITICAL_SECTION lock;   
264 } s_xbt_mutex_t;
265
266 xbt_mutex_t xbt_mutex_init(void) {
267    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
268
269    /* initialize the critical section object */
270    InitializeCriticalSection(&(res->lock));
271    
272    return res;
273 }
274
275 void xbt_mutex_lock(xbt_mutex_t mutex) {
276
277    EnterCriticalSection(& mutex->lock);
278 }
279
280 void xbt_mutex_unlock(xbt_mutex_t mutex) {
281
282    LeaveCriticalSection (& mutex->lock);
283
284 }
285
286 void xbt_mutex_destroy(xbt_mutex_t mutex) {
287
288    if (!mutex) return;
289    
290    DeleteCriticalSection(& mutex->lock);                
291    free(mutex);
292 }
293
294 /***** condition related functions *****/
295  enum {
296     SIGNAL = 0,
297     BROADCAST = 1,
298     MAX_EVENTS = 2
299  };
300
301 typedef struct xbt_thcond_ {
302    HANDLE events[MAX_EVENTS];
303    
304    unsigned int waiters_count;           /* the number of waiters                        */
305    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
306 } s_xbt_thcond_t;
307
308 xbt_thcond_t xbt_thcond_init(void) {
309
310    xbt_thcond_t res = xbt_new0(s_xbt_thcond_t,1);
311         
312    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
313         
314    /* initialize the critical section object */
315    InitializeCriticalSection(& res->waiters_count_lock);
316         
317    res->waiters_count = 0;
318         
319    /* Create an auto-reset event */
320    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); 
321         
322    if(!res->events[SIGNAL]){
323       DeleteCriticalSection(& res->waiters_count_lock);
324       free(res);
325       THROW0(system_error,0,"CreateEvent failed for the signals");
326    }
327         
328    /* Create a manual-reset event. */
329    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
330         
331    if(!res->events[BROADCAST]){
332                 
333       DeleteCriticalSection(& res->waiters_count_lock);         
334       CloseHandle(res->events[SIGNAL]);
335       free(res); 
336       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
337    }
338
339    return res;
340 }
341
342 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
343         
344    unsigned long wait_result;
345    int is_last_waiter;
346
347    /* lock the threads counter and increment it */
348    EnterCriticalSection (& cond->waiters_count_lock);
349    cond->waiters_count++;
350    LeaveCriticalSection (& cond->waiters_count_lock);
351                 
352    /* unlock the mutex associate with the condition */
353    LeaveCriticalSection (& mutex->lock);
354         
355    /* wait for a signal (broadcast or no) */
356    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
357         
358    if(wait_result == WAIT_FAILED)
359      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
360         
361    /* we have a signal lock the condition */
362    EnterCriticalSection (& cond->waiters_count_lock);
363    cond->waiters_count--;
364         
365    /* it's the last waiter or it's a broadcast ? */
366    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
367         
368    LeaveCriticalSection (& cond->waiters_count_lock);
369         
370    /* yes it's the last waiter or it's a broadcast
371     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
372     * by the system. 
373     */
374    if (is_last_waiter)
375       if(!ResetEvent (cond->events[BROADCAST]))
376         THROW0(system_error,0,"ResetEvent failed");
377         
378    /* relock the mutex associated with the condition in accordance with the posix thread specification */
379    EnterCriticalSection (& mutex->lock);
380 }
381
382 void xbt_thcond_signal(xbt_thcond_t cond) {
383    int have_waiters;
384
385    EnterCriticalSection (& cond->waiters_count_lock);
386    have_waiters = cond->waiters_count > 0;
387    LeaveCriticalSection (& cond->waiters_count_lock);
388         
389    if (have_waiters)
390      if(!SetEvent(cond->events[SIGNAL]))
391        THROW0(system_error,0,"SetEvent failed");
392        
393    xbt_thread_yield();
394 }
395
396 void xbt_thcond_broadcast(xbt_thcond_t cond){
397    int have_waiters;
398
399    EnterCriticalSection (& cond->waiters_count_lock);
400    have_waiters = cond->waiters_count > 0;
401    LeaveCriticalSection (& cond->waiters_count_lock);
402         
403    if (have_waiters)
404      SetEvent(cond->events[BROADCAST]);
405 }
406
407 void xbt_thcond_destroy(xbt_thcond_t cond){
408    int error = 0;
409    
410    if (!cond) return;
411    
412    if(!CloseHandle(cond->events[SIGNAL]))
413      error = 1;
414         
415    if(!CloseHandle(cond->events[BROADCAST]))
416      error = 1;
417         
418    DeleteCriticalSection(& cond->waiters_count_lock);
419         
420    xbt_free(cond);
421    
422    if (error)
423      THROW0(system_error,0,"Error while destroying the condition");
424 }
425
426 #endif