Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Make the implementation more robust: don't die if something to destroy is already...
[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 } s_xbt_thread_t ;
26
27 /* thread-specific data containing the xbt_thread_t structure */
28 static pthread_key_t xbt_self_thread_key;
29
30 /* frees the xbt_thread_t corresponding to the current thread */
31 static void xbt_thread_free_thread_data(void*d){
32    free(d);
33 }
34
35 void xbt_thread_mod_init(void) {
36    int errcode;
37    
38    if ((errcode=pthread_key_create(&xbt_self_thread_key, &xbt_thread_free_thread_data)))
39      THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key");
40 }
41 void xbt_thread_mod_exit(void) {
42    /* FIXME: don't try to free our key on shutdown. Valgrind detects no leak if we don't, and whine if we try to */
43 //   int errcode;
44    
45 //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
46 //     THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
47 }
48
49
50 xbt_thread_t xbt_thread_create(pvoid_f_pvoid_t start_routine,
51                                void* param)  {
52    xbt_thread_t res = xbt_new(s_xbt_thread_t,1);
53    int errcode;
54
55    if ((errcode=pthread_setspecific(xbt_self_thread_key,res)))
56      THROW0(system_error,errcode,"pthread_setspecific failed for xbt_self_thread_key");
57       
58    if ((errcode = pthread_create(&(res->t), NULL, start_routine, param)))
59      THROW0(system_error,errcode, "pthread_create failed");
60    
61    return res;
62 }                      
63 void xbt_thread_exit(int *retval) {
64    pthread_exit(retval);
65 }
66 xbt_thread_t xbt_thread_self(void) {
67    return pthread_getspecific(xbt_self_thread_key);
68 }
69
70 #include <sched.h>
71 void xbt_thread_yield(void) {
72    sched_yield();
73 }
74 /****** mutex related functions ******/
75 typedef struct xbt_mutex_ {
76    pthread_mutex_t m;
77 } s_xbt_mutex_t;
78
79 xbt_mutex_t xbt_mutex_init(void) {
80    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
81    int errcode;
82    
83    if ((errcode = pthread_mutex_init(&(res->m),NULL)))
84      THROW0(system_error,errcode,"pthread_mutex_init() failed");
85    
86    return res;
87 }
88
89 void xbt_mutex_lock(xbt_mutex_t mutex) {
90    int errcode;
91    
92    if ((errcode=pthread_mutex_lock(&(mutex->m))))
93      THROW1(system_error,errcode,"pthread_mutex_lock(%p) failed",mutex);
94 }
95
96 void xbt_mutex_unlock(xbt_mutex_t mutex) {
97    int errcode;
98    
99    if ((errcode=pthread_mutex_unlock(&(mutex->m))))
100      THROW1(system_error,errcode,"pthread_mutex_unlock(%p) failed",mutex);
101 }
102
103 void xbt_mutex_destroy(xbt_mutex_t mutex) {
104    int errcode;
105    
106    if (!mutex) return;
107    
108    if ((errcode=pthread_mutex_destroy(&(mutex->m))))
109      THROW1(system_error,errcode,"pthread_mutex_destroy(%p) failed",mutex);
110    free(mutex);
111 }
112
113 /***** condition related functions *****/
114 typedef struct xbt_thcond_ {
115    pthread_cond_t c;
116 } s_xbt_thcond_t;
117
118 xbt_thcond_t xbt_thcond_init(void) {
119    xbt_thcond_t res = xbt_new(s_xbt_thcond_t,1);
120    int errcode;
121    if ((errcode=pthread_cond_init(&(res->c),NULL)))
122      THROW0(system_error,errcode,"pthread_cond_init() failed");
123
124    return res;
125 }
126
127 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
128    int errcode;
129    if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m))))
130      THROW2(system_error,errcode,"pthread_cond_wait(%p,%p) failed",cond,mutex);
131 }
132
133 void xbt_thcond_signal(xbt_thcond_t cond) {
134    int errcode;
135    if ((errcode=pthread_cond_signal(&(cond->c))))
136      THROW1(system_error,errcode,"pthread_cond_signal(%p) failed",cond);
137 }
138          
139 void xbt_thcond_broadcast(xbt_thcond_t cond){
140    int errcode;
141    if ((errcode=pthread_cond_broadcast(&(cond->c))))
142      THROW1(system_error,errcode,"pthread_cond_broadcast(%p) failed",cond);
143 }
144 void xbt_thcond_destroy(xbt_thcond_t cond){
145    int errcode;
146
147    if (!cond) return;
148
149    if ((errcode=pthread_cond_destroy(&(cond->c))))
150      THROW1(system_error,errcode,"pthread_cond_destroy(%p) failed",cond);
151    free(cond);
152 }
153
154 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
155
156 #elif defined(WIN32)
157
158 typedef struct xbt_thread_ {
159    HANDLE handle;                  /* the win thread handle        */
160    unsigned long id;               /* the win thread id            */
161 } s_xbt_thread_t ;
162
163 /* key to the TLS containing the xbt_thread_t structure */
164 static unsigned long xbt_self_thread_key;
165
166 void xbt_thread_mod_init(void) {
167    xbt_self_thread_key = TlsAlloc();
168 }
169 void xbt_thread_mod_exit(void) {
170    int errcode;
171    if (!(errcode = TlsFree(xbt_self_thread_key))) 
172      THROW0(system_error,errcode,"TlsFree() failed to cleanup the thread submodule");
173 }
174
175 xbt_thread_t xbt_thread_create(pvoid_f_pvoid_t start_routine,
176                                void* param)  {
177    
178    xbt_thread_t res = xbt_new(s_xbt_thread_t,1);
179    
180    res->handle = CreateThread(NULL,0, 
181                               (LPTHREAD_START_ROUTINE)start_routine,
182                               param,0,& res->id);
183         
184    if(!res->handle) {
185      xbt_free(res);
186      THROW0(system_error,0,"CreateThread failed");
187    }
188    
189    if(!TlsSetValue(xbt_self_thread_key,res))
190      THROW0(system_error,0,"TlsSetValue of data describing the created thread failed");
191      
192    return res;
193 }
194
195 void xbt_thread_exit(int *retval) {
196    xbt_thread_t self = xbt_thread_self();
197    
198    CloseHandle(self->handle);
199    free(self);
200    
201    ExitThread(*retval);
202 }
203
204 xbt_thread_t xbt_thread_self(void) {
205    return TlsGetValue(xbt_self_thread_key);
206 }
207
208 void xbt_thread_yield(void) {
209     Sleep(0);
210 }
211
212 /****** mutex related functions ******/
213 typedef struct xbt_mutex_ {
214    CRITICAL_SECTION lock;   
215 } s_xbt_mutex_t;
216
217 xbt_mutex_t xbt_mutex_init(void) {
218    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
219
220    /* initialize the critical section object */
221    InitializeCriticalSection(&(res->lock));
222    
223    return res;
224 }
225
226 void xbt_mutex_lock(xbt_mutex_t mutex) {
227
228    EnterCriticalSection(& mutex->lock);
229 }
230
231 void xbt_mutex_unlock(xbt_mutex_t mutex) {
232
233    LeaveCriticalSection (& mutex->lock);
234
235 }
236
237 void xbt_mutex_destroy(xbt_mutex_t mutex) {
238
239    if (!mutex) return;
240    
241    DeleteCriticalSection(& mutex->lock);                
242    free(mutex);
243 }
244
245 /***** condition related functions *****/
246  enum {
247     SIGNAL = 0,
248     BROADCAST = 1,
249     MAX_EVENTS = 2
250  };
251
252 typedef struct xbt_thcond_ {
253    HANDLE events[MAX_EVENTS];
254    
255    unsigned int waiters_count;           /* the number of waiters                        */
256    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
257 } s_xbt_thcond_t;
258
259 xbt_thcond_t xbt_thcond_init(void) {
260
261    xbt_thcond_t res = xbt_new0(s_xbt_thcond_t,1);
262         
263    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
264         
265    /* initialize the critical section object */
266    InitializeCriticalSection(& res->waiters_count_lock);
267         
268    res->waiters_count = 0;
269         
270    /* Create an auto-reset event */
271    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); 
272         
273    if(!res->events[SIGNAL]){
274       DeleteCriticalSection(& res->waiters_count_lock);
275       free(res);
276       THROW0(system_error,0,"CreateEvent failed for the signals");
277    }
278         
279    /* Create a manual-reset event. */
280    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
281         
282    if(!res->events[BROADCAST]){
283                 
284       DeleteCriticalSection(& res->waiters_count_lock);         
285       CloseHandle(res->events[SIGNAL]);
286       free(res); 
287       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
288    }
289
290    return res;
291 }
292
293 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
294         
295    unsigned long wait_result;
296    int is_last_waiter;
297
298    /* lock the threads counter and increment it */
299    EnterCriticalSection (& cond->waiters_count_lock);
300    cond->waiters_count++;
301    LeaveCriticalSection (& cond->waiters_count_lock);
302                 
303    /* unlock the mutex associate with the condition */
304    LeaveCriticalSection (& mutex->lock);
305         
306    /* wait for a signal (broadcast or no) */
307    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
308         
309    if(wait_result == WAIT_FAILED)
310      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
311         
312    /* we have a signal lock the condition */
313    EnterCriticalSection (& cond->waiters_count_lock);
314    cond->waiters_count--;
315         
316    /* it's the last waiter or it's a broadcast ? */
317    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
318         
319    LeaveCriticalSection (& cond->waiters_count_lock);
320         
321    /* yes it's the last waiter or it's a broadcast
322     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
323     * by the system. 
324     */
325    if (is_last_waiter)
326       if(!ResetEvent (cond->events[BROADCAST]))
327         THROW0(system_error,0,"ResetEvent failed");
328         
329    /* relock the mutex associated with the condition in accordance with the posix thread specification */
330    EnterCriticalSection (& mutex->lock);
331 }
332
333 void xbt_thcond_signal(xbt_thcond_t cond) {
334    int have_waiters;
335
336    EnterCriticalSection (& cond->waiters_count_lock);
337    have_waiters = cond->waiters_count > 0;
338    LeaveCriticalSection (& cond->waiters_count_lock);
339         
340    if (have_waiters)
341      if(!SetEvent(cond->events[SIGNAL]))
342        THROW0(system_error,0,"SetEvent failed");
343 }
344
345 void xbt_thcond_broadcast(xbt_thcond_t cond){
346    int have_waiters;
347
348    EnterCriticalSection (& cond->waiters_count_lock);
349    have_waiters = cond->waiters_count > 0;
350    LeaveCriticalSection (& cond->waiters_count_lock);
351         
352    if (have_waiters)
353      SetEvent(cond->events[BROADCAST]);
354 }
355
356 void xbt_thcond_destroy(xbt_thcond_t cond){
357    int error = 0;
358    
359    if (!cond) return;
360    
361    if(!CloseHandle(cond->events[SIGNAL]))
362      error = 1;
363         
364    if(!CloseHandle(cond->events[BROADCAST]))
365      error = 1;
366         
367    DeleteCriticalSection(& cond->waiters_count_lock);
368         
369    xbt_free(cond);
370    
371    if (error)
372      THROW0(system_error,0,"Error while destroying the condition");
373 }
374
375 #endif