Logo AND Algorithmique Numérique Distribuée

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