Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0aef1c1549db8ff307a954bfe03381231bcaba4c
[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      THROW1(system_error,errcode, "pthread_create failed: %s",strerror(errcode));
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                 THROW1(system_error,errcode, "pthread_join failed: %s",
82                        strerror(errcode));
83         free(thread);   
84 }                      
85
86 void xbt_thread_exit(int *retval) {
87    pthread_exit(retval);
88 }
89
90 xbt_thread_t xbt_thread_self(void) {
91    return pthread_getspecific(xbt_self_thread_key);
92 }
93
94 #include <sched.h>
95 void xbt_thread_yield(void) {
96    sched_yield();
97 }
98 /****** mutex related functions ******/
99 typedef struct xbt_mutex_ {
100    pthread_mutex_t m;
101 } s_xbt_mutex_t;
102
103 xbt_mutex_t xbt_mutex_init(void) {
104    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
105    int errcode;
106    
107    if ((errcode = pthread_mutex_init(&(res->m),NULL)))
108      THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",
109             strerror(errcode));
110    
111    return res;
112 }
113
114 void xbt_mutex_lock(xbt_mutex_t mutex) {
115    int errcode;
116    
117    if ((errcode=pthread_mutex_lock(&(mutex->m))))
118      THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s",
119             mutex, strerror(errcode));
120 }
121
122 void xbt_mutex_unlock(xbt_mutex_t mutex) {
123    int errcode;
124    
125    if ((errcode=pthread_mutex_unlock(&(mutex->m))))
126      THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s",
127             mutex, strerror(errcode));
128 }
129
130 void xbt_mutex_destroy(xbt_mutex_t mutex) {
131    int errcode;
132    
133    if (!mutex) return;
134    
135    if ((errcode=pthread_mutex_destroy(&(mutex->m))))
136      THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s",
137             mutex, strerror(errcode));
138    free(mutex);
139 }
140
141 /***** condition related functions *****/
142 typedef struct xbt_thcond_ {
143    pthread_cond_t c;
144 } s_xbt_thcond_t;
145
146 xbt_thcond_t xbt_thcond_init(void) {
147    xbt_thcond_t res = xbt_new(s_xbt_thcond_t,1);
148    int errcode;
149    if ((errcode=pthread_cond_init(&(res->c),NULL)))
150      THROW1(system_error,errcode,"pthread_cond_init() failed: %s",
151             strerror(errcode));
152
153    return res;
154 }
155
156 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
157    int errcode;
158    if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m))))
159      THROW3(system_error,errcode,"pthread_cond_wait(%p,%p) failed: %s",
160             cond,mutex, strerror(errcode));
161 }
162
163 void xbt_thcond_signal(xbt_thcond_t cond) {
164    int errcode;
165    if ((errcode=pthread_cond_signal(&(cond->c))))
166      THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s",
167             cond, strerror(errcode));
168 }
169          
170 void xbt_thcond_broadcast(xbt_thcond_t cond){
171    int errcode;
172    if ((errcode=pthread_cond_broadcast(&(cond->c))))
173      THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s",
174             cond, strerror(errcode));
175 }
176 void xbt_thcond_destroy(xbt_thcond_t cond){
177    int errcode;
178
179    if (!cond) return;
180
181    if ((errcode=pthread_cond_destroy(&(cond->c))))
182      THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s",
183             cond, strerror(errcode));
184    free(cond);
185 }
186
187 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
188
189 #elif defined(WIN32)
190
191 typedef struct xbt_thread_ {
192   HANDLE handle;                  /* the win thread handle        */
193   unsigned long id;               /* the win thread id            */
194   pvoid_f_pvoid_t *start_routine;
195   void* param;
196 } s_xbt_thread_t ;
197
198 /* key to the TLS containing the xbt_thread_t structure */
199 static unsigned long xbt_self_thread_key;
200
201 void xbt_thread_mod_init(void) {
202    xbt_self_thread_key = TlsAlloc();
203 }
204 void xbt_thread_mod_exit(void) {
205    
206    if (!TlsFree(xbt_self_thread_key)) 
207      THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
208 }
209
210 static DWORD WINAPI  wrapper_start_routine(void *s) {
211   xbt_thread_t t = (xbt_thread_t)s;
212  
213     if(!TlsSetValue(xbt_self_thread_key,t))
214      THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
215    
216    return (DWORD)t->start_routine(t->param);
217 }
218
219
220 xbt_thread_t xbt_thread_create(pvoid_f_pvoid_t start_routine,
221                                void* param)  {
222    
223    xbt_thread_t t = xbt_new(s_xbt_thread_t,1);
224
225    t->start_routine = start_routine ;
226    t->param = param;
227    
228    t->handle = CreateThread(NULL,0,
229                             (LPTHREAD_START_ROUTINE)wrapper_start_routine,
230                             t,0,&(t->id));
231         
232    if(!t->handle) {
233      xbt_free(t);
234      THROW0(system_error,(int)GetLastError(),"CreateThread failed");
235    }
236    
237    return t;
238 }
239
240 void 
241 xbt_thread_join(xbt_thread_t thread,void ** thread_return) {
242
243         if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))  
244                 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
245                 
246         if(thread_return){
247                 
248                 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
249                         THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
250         }
251         
252         CloseHandle(thread->handle);
253         free(thread);
254 }
255
256 void xbt_thread_exit(int *retval) {
257    if(retval)
258         ExitThread(*retval);
259    else
260         ExitThread(0);
261 }
262
263 xbt_thread_t xbt_thread_self(void) {
264    return TlsGetValue(xbt_self_thread_key);
265 }
266
267 void xbt_thread_yield(void) {
268     Sleep(0);
269 }
270
271 /****** mutex related functions ******/
272 typedef struct xbt_mutex_ {
273    CRITICAL_SECTION lock;   
274 } s_xbt_mutex_t;
275
276 xbt_mutex_t xbt_mutex_init(void) {
277    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
278
279    /* initialize the critical section object */
280    InitializeCriticalSection(&(res->lock));
281    
282    return res;
283 }
284
285 void xbt_mutex_lock(xbt_mutex_t mutex) {
286
287    EnterCriticalSection(& mutex->lock);
288 }
289
290 void xbt_mutex_unlock(xbt_mutex_t mutex) {
291
292    LeaveCriticalSection (& mutex->lock);
293
294 }
295
296 void xbt_mutex_destroy(xbt_mutex_t mutex) {
297
298    if (!mutex) return;
299    
300    DeleteCriticalSection(& mutex->lock);                
301    free(mutex);
302 }
303
304 /***** condition related functions *****/
305  enum {
306     SIGNAL = 0,
307     BROADCAST = 1,
308     MAX_EVENTS = 2
309  };
310
311 typedef struct xbt_thcond_ {
312    HANDLE events[MAX_EVENTS];
313    
314    unsigned int waiters_count;           /* the number of waiters                        */
315    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
316 } s_xbt_thcond_t;
317
318 xbt_thcond_t xbt_thcond_init(void) {
319
320    xbt_thcond_t res = xbt_new0(s_xbt_thcond_t,1);
321         
322    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
323         
324    /* initialize the critical section object */
325    InitializeCriticalSection(& res->waiters_count_lock);
326         
327    res->waiters_count = 0;
328         
329    /* Create an auto-reset event */
330    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); 
331         
332    if(!res->events[SIGNAL]){
333       DeleteCriticalSection(& res->waiters_count_lock);
334       free(res);
335       THROW0(system_error,0,"CreateEvent failed for the signals");
336    }
337         
338    /* Create a manual-reset event. */
339    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
340         
341    if(!res->events[BROADCAST]){
342                 
343       DeleteCriticalSection(& res->waiters_count_lock);         
344       CloseHandle(res->events[SIGNAL]);
345       free(res); 
346       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
347    }
348
349    return res;
350 }
351
352 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
353         
354    unsigned long wait_result;
355    int is_last_waiter;
356
357    /* lock the threads counter and increment it */
358    EnterCriticalSection (& cond->waiters_count_lock);
359    cond->waiters_count++;
360    LeaveCriticalSection (& cond->waiters_count_lock);
361                 
362    /* unlock the mutex associate with the condition */
363    LeaveCriticalSection (& mutex->lock);
364         
365    /* wait for a signal (broadcast or no) */
366    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
367         
368    if(wait_result == WAIT_FAILED)
369      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
370         
371    /* we have a signal lock the condition */
372    EnterCriticalSection (& cond->waiters_count_lock);
373    cond->waiters_count--;
374         
375    /* it's the last waiter or it's a broadcast ? */
376    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
377         
378    LeaveCriticalSection (& cond->waiters_count_lock);
379         
380    /* yes it's the last waiter or it's a broadcast
381     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
382     * by the system. 
383     */
384    if (is_last_waiter)
385       if(!ResetEvent (cond->events[BROADCAST]))
386         THROW0(system_error,0,"ResetEvent failed");
387         
388    /* relock the mutex associated with the condition in accordance with the posix thread specification */
389    EnterCriticalSection (& mutex->lock);
390 }
391
392 void xbt_thcond_signal(xbt_thcond_t cond) {
393    int have_waiters;
394
395    EnterCriticalSection (& cond->waiters_count_lock);
396    have_waiters = cond->waiters_count > 0;
397    LeaveCriticalSection (& cond->waiters_count_lock);
398         
399    if (have_waiters)
400      if(!SetEvent(cond->events[SIGNAL]))
401        THROW0(system_error,0,"SetEvent failed");
402        
403    xbt_thread_yield();
404 }
405
406 void xbt_thcond_broadcast(xbt_thcond_t cond){
407    int have_waiters;
408
409    EnterCriticalSection (& cond->waiters_count_lock);
410    have_waiters = cond->waiters_count > 0;
411    LeaveCriticalSection (& cond->waiters_count_lock);
412         
413    if (have_waiters)
414      SetEvent(cond->events[BROADCAST]);
415 }
416
417 void xbt_thcond_destroy(xbt_thcond_t cond){
418    int error = 0;
419    
420    if (!cond) return;
421    
422    if(!CloseHandle(cond->events[SIGNAL]))
423      error = 1;
424         
425    if(!CloseHandle(cond->events[BROADCAST]))
426      error = 1;
427         
428    DeleteCriticalSection(& cond->waiters_count_lock);
429         
430    xbt_free(cond);
431    
432    if (error)
433      THROW0(system_error,0,"Error while destroying the condition");
434 }
435
436 #endif