Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
3a6d8d0010bf2bbfd63f5724983f473ac871eba9
[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 } s_xbt_thread_t ;
184
185 typedef struct s_xbt_thread_wrapper_for_restart__ {
186   pvoid_f_pvoid_t *start_routine;
187   void* param;
188   xbt_thread_t res;
189 } s_xbt_thread_wrapper_for_restart_t, *xbt_thread_wrapper_for_restart_t;
190
191 /* key to the TLS containing the xbt_thread_t structure */
192 static unsigned long xbt_self_thread_key;
193
194 void xbt_thread_mod_init(void) {
195    xbt_self_thread_key = TlsAlloc();
196 }
197 void xbt_thread_mod_exit(void) {
198    
199    if (!TlsFree(xbt_self_thread_key)) 
200      THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
201 }
202
203 DWORD WINAPI  wrapper_start_routine(void *s) {
204   xbt_thread_wrapper_for_restart_t stub = (xbt_thread_wrapper_for_restart_t)s;
205  
206     if(!TlsSetValue(xbt_self_thread_key,stub->res))
207      THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
208    
209    return (DWORD)stub->start_routine(stub->param);
210 }
211
212
213 xbt_thread_t xbt_thread_create(pvoid_f_pvoid_t start_routine,
214                                void* param)  {
215    
216    xbt_thread_wrapper_for_restart_t stub = xbt_new0(s_xbt_thread_wrapper_for_restart_t,1);
217
218    stub->start_routine = start_routine ;
219    stub->param = param;
220    stub->res = xbt_new(s_xbt_thread_t,1);
221    
222    stub->res->handle = CreateThread(NULL,0,
223                               (LPTHREAD_START_ROUTINE)wrapper_start_routine,
224                               stub,0,&(stub->res->id));
225         
226    if(!stub->res->handle) {
227      xbt_free(stub->res);
228      THROW0(system_error,(int)GetLastError(),"CreateThread failed");
229    }
230    
231    return stub->res;
232 }
233
234 void 
235 xbt_thread_join(xbt_thread_t thread,void ** thread_return) {
236
237         if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))  
238                 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
239                 
240         if(thread_return){
241                 
242                 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
243                         THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
244         }
245         
246         CloseHandle(thread->handle);
247 }
248
249 void xbt_thread_exit(int *retval) {
250    
251    xbt_thread_t self = xbt_thread_self();
252    
253    if(retval)
254         ExitThread(*retval);
255    else
256         ExitThread(0);
257 }
258
259 xbt_thread_t xbt_thread_self(void) {
260    return TlsGetValue(xbt_self_thread_key);
261 }
262
263 void xbt_thread_yield(void) {
264     Sleep(0);
265 }
266
267 /****** mutex related functions ******/
268 typedef struct xbt_mutex_ {
269    CRITICAL_SECTION lock;   
270 } s_xbt_mutex_t;
271
272 xbt_mutex_t xbt_mutex_init(void) {
273    xbt_mutex_t res = xbt_new(s_xbt_mutex_t,1);
274
275    /* initialize the critical section object */
276    InitializeCriticalSection(&(res->lock));
277    
278    return res;
279 }
280
281 void xbt_mutex_lock(xbt_mutex_t mutex) {
282
283    EnterCriticalSection(& mutex->lock);
284 }
285
286 void xbt_mutex_unlock(xbt_mutex_t mutex) {
287
288    LeaveCriticalSection (& mutex->lock);
289
290 }
291
292 void xbt_mutex_destroy(xbt_mutex_t mutex) {
293
294    if (!mutex) return;
295    
296    DeleteCriticalSection(& mutex->lock);                
297    free(mutex);
298 }
299
300 /***** condition related functions *****/
301  enum {
302     SIGNAL = 0,
303     BROADCAST = 1,
304     MAX_EVENTS = 2
305  };
306
307 typedef struct xbt_thcond_ {
308    HANDLE events[MAX_EVENTS];
309    
310    unsigned int waiters_count;           /* the number of waiters                        */
311    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
312 } s_xbt_thcond_t;
313
314 xbt_thcond_t xbt_thcond_init(void) {
315
316    xbt_thcond_t res = xbt_new0(s_xbt_thcond_t,1);
317         
318    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
319         
320    /* initialize the critical section object */
321    InitializeCriticalSection(& res->waiters_count_lock);
322         
323    res->waiters_count = 0;
324         
325    /* Create an auto-reset event */
326    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); 
327         
328    if(!res->events[SIGNAL]){
329       DeleteCriticalSection(& res->waiters_count_lock);
330       free(res);
331       THROW0(system_error,0,"CreateEvent failed for the signals");
332    }
333         
334    /* Create a manual-reset event. */
335    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
336         
337    if(!res->events[BROADCAST]){
338                 
339       DeleteCriticalSection(& res->waiters_count_lock);         
340       CloseHandle(res->events[SIGNAL]);
341       free(res); 
342       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
343    }
344
345    return res;
346 }
347
348 void xbt_thcond_wait(xbt_thcond_t cond, xbt_mutex_t mutex) {
349         
350    unsigned long wait_result;
351    int is_last_waiter;
352
353    /* lock the threads counter and increment it */
354    EnterCriticalSection (& cond->waiters_count_lock);
355    cond->waiters_count++;
356    LeaveCriticalSection (& cond->waiters_count_lock);
357                 
358    /* unlock the mutex associate with the condition */
359    LeaveCriticalSection (& mutex->lock);
360         
361    /* wait for a signal (broadcast or no) */
362    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
363         
364    if(wait_result == WAIT_FAILED)
365      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
366         
367    /* we have a signal lock the condition */
368    EnterCriticalSection (& cond->waiters_count_lock);
369    cond->waiters_count--;
370         
371    /* it's the last waiter or it's a broadcast ? */
372    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
373         
374    LeaveCriticalSection (& cond->waiters_count_lock);
375         
376    /* yes it's the last waiter or it's a broadcast
377     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
378     * by the system. 
379     */
380    if (is_last_waiter)
381       if(!ResetEvent (cond->events[BROADCAST]))
382         THROW0(system_error,0,"ResetEvent failed");
383         
384    /* relock the mutex associated with the condition in accordance with the posix thread specification */
385    EnterCriticalSection (& mutex->lock);
386 }
387
388 void xbt_thcond_signal(xbt_thcond_t cond) {
389    int have_waiters;
390
391    EnterCriticalSection (& cond->waiters_count_lock);
392    have_waiters = cond->waiters_count > 0;
393    LeaveCriticalSection (& cond->waiters_count_lock);
394         
395    if (have_waiters)
396      if(!SetEvent(cond->events[SIGNAL]))
397        THROW0(system_error,0,"SetEvent failed");
398 }
399
400 void xbt_thcond_broadcast(xbt_thcond_t cond){
401    int have_waiters;
402
403    EnterCriticalSection (& cond->waiters_count_lock);
404    have_waiters = cond->waiters_count > 0;
405    LeaveCriticalSection (& cond->waiters_count_lock);
406         
407    if (have_waiters)
408      SetEvent(cond->events[BROADCAST]);
409 }
410
411 void xbt_thcond_destroy(xbt_thcond_t cond){
412    int error = 0;
413    
414    if (!cond) return;
415    
416    if(!CloseHandle(cond->events[SIGNAL]))
417      error = 1;
418         
419    if(!CloseHandle(cond->events[BROADCAST]))
420      error = 1;
421         
422    DeleteCriticalSection(& cond->waiters_count_lock);
423         
424    xbt_free(cond);
425    
426    if (error)
427      THROW0(system_error,0,"Error while destroying the condition");
428 }
429
430 #endif