Logo AND Algorithmique Numérique Distribuée

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