Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
dad3c664614604cc8cfe257027d74aba5e454f5c
[simgrid.git] / src / xbt / xbt_os_thread.c
1 /* $Id$ */
2
3 /* xbt_os_thread -- portability layer over the pthread API                  */
4 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD     */
5 /* in SG, when using CONTEXT_UCONTEXT, xbt_os_thread_stub is used instead   */
6
7 /* Copyright 2006,2007 Malek Cherier, Martin Quinson          
8  * All right reserved.                                                      */
9
10 /* This program is free software; you can redistribute it and/or modify it
11  * under the terms of the license (GNU LGPL) which comes with this package. */
12
13 #include "xbt/sysdep.h"
14 #include "xbt/ex.h"
15 #include "xbt/ex_interface.h" /* We play crude games with exceptions */
16 #include "portable.h"
17 #include "xbt/xbt_os_time.h" /* Portable time facilities */
18 #include "xbt/xbt_os_thread.h" /* This module */
19 #include "xbt_modinter.h" /* Initialization/finalization of this module */
20
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os,xbt,"Synchronization mechanism (OS-level)");
22
23 /* ********************************* PTHREAD IMPLEMENTATION ************************************ */
24 #ifdef HAVE_PTHREAD_H
25 #include <pthread.h>
26
27
28 typedef struct xbt_os_thread_ {
29    pthread_t t;
30    char *name;
31    void *param;
32    pvoid_f_pvoid_t *start_routine;
33    ex_ctx_t *exception;
34 } s_xbt_os_thread_t ;
35 static xbt_os_thread_t main_thread = NULL;
36
37 /* thread-specific data containing the xbt_os_thread_t structure */
38 static pthread_key_t xbt_self_thread_key;
39 static int thread_mod_inited = 0;
40
41 /* frees the xbt_os_thread_t corresponding to the current thread */
42 static void xbt_os_thread_free_thread_data(void*d){
43    free(d);
44 }
45
46 /* callback: context fetching */
47 static ex_ctx_t *_os_thread_ex_ctx(void) {
48   return xbt_os_thread_self()->exception;
49 }
50
51 /* callback: termination */
52 static void _os_thread_ex_terminate(xbt_ex_t * e) {
53   xbt_ex_display(e);
54
55   abort();
56   /* FIXME: there should be a configuration variable to choose to kill everyone or only this one */
57 }
58
59 void xbt_os_thread_mod_init(void) {
60    int errcode;
61    
62    if (thread_mod_inited)
63      return;
64    
65    if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL)))
66      THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key");
67
68    main_thread=xbt_new(s_xbt_os_thread_t,1);
69    main_thread->name = (char*)"main";
70    main_thread->start_routine = NULL;
71    main_thread->param = NULL;
72    main_thread->exception = xbt_new(ex_ctx_t, 1);
73    XBT_CTX_INITIALIZE(main_thread->exception);
74
75    thread_mod_inited = 1;
76 }
77 void xbt_os_thread_mod_exit(void) {
78    /* FIXME: don't try to free our key on shutdown. 
79       Valgrind detects no leak if we don't, and whine if we try to */
80 //   int errcode;
81    
82 //   if ((errcode=pthread_key_delete(xbt_self_thread_key)))
83 //     THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key");
84 }
85
86 static void * wrapper_start_routine(void *s) {
87   xbt_os_thread_t t = s;   
88   int errcode;
89
90   if ((errcode=pthread_setspecific(xbt_self_thread_key,t)))
91     THROW0(system_error,errcode,
92            "pthread_setspecific failed for xbt_self_thread_key");   
93   return t->start_routine(t->param);
94 }
95 xbt_os_thread_t xbt_os_thread_create(const char*name,
96                                      pvoid_f_pvoid_t start_routine,
97                                      void* param)  {
98    int errcode;
99
100    xbt_os_thread_t res_thread=xbt_new(s_xbt_os_thread_t,1);
101    res_thread->name = xbt_strdup(name);
102    res_thread->start_routine = start_routine;
103    res_thread->param = param;
104    res_thread->exception = xbt_new(ex_ctx_t, 1);
105    XBT_CTX_INITIALIZE(res_thread->exception);
106    
107    if ((errcode = pthread_create(&(res_thread->t), NULL, 
108                                  wrapper_start_routine, res_thread)))
109      THROW1(system_error,errcode, 
110             "pthread_create failed: %s",strerror(errcode));
111
112    return res_thread;
113 }
114
115 const char* xbt_os_thread_name(xbt_os_thread_t t) {
116    return t->name;
117 }
118
119 const char* xbt_os_thread_self_name(void) {
120    xbt_os_thread_t self = xbt_os_thread_self();
121    return self?self->name:"main";
122 }
123 void 
124 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
125         
126   int errcode;   
127   
128   if ((errcode = pthread_join(thread->t,thread_return)))
129     THROW1(system_error,errcode, "pthread_join failed: %s",
130            strerror(errcode));
131    if (thread->exception)
132      free(thread->exception);
133
134    if (thread == main_thread) /* just killed main thread */
135      main_thread = NULL;
136
137    free(thread);   
138 }                      
139
140 void xbt_os_thread_exit(int *retval) {
141    pthread_exit(retval);
142 }
143
144 xbt_os_thread_t xbt_os_thread_self(void) {
145   xbt_os_thread_t res;
146
147   if (!thread_mod_inited)
148     return NULL;
149   
150   res = pthread_getspecific(xbt_self_thread_key);
151   if (!res)
152     res = main_thread;
153
154   return res;
155 }
156
157 #include <sched.h>
158 void xbt_os_thread_yield(void) {
159    sched_yield();
160 }
161 void xbt_os_thread_cancel(xbt_os_thread_t t) {
162    pthread_cancel(t->t);
163 }
164 /****** mutex related functions ******/
165 typedef struct xbt_os_mutex_ {
166   /* KEEP IT IN SYNC WITH xbt_thread.c */
167    pthread_mutex_t m;
168 } s_xbt_os_mutex_t;
169
170 xbt_os_mutex_t xbt_os_mutex_init(void) {
171    xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
172    int errcode;
173    
174    if ((errcode = pthread_mutex_init(&(res->m),NULL)))
175      THROW1(system_error,errcode,"pthread_mutex_init() failed: %s",
176             strerror(errcode));
177    
178    return res;
179 }
180
181 void xbt_os_mutex_lock(xbt_os_mutex_t mutex) {
182    int errcode;
183    
184    if ((errcode=pthread_mutex_lock(&(mutex->m))))
185      THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s",
186             mutex, strerror(errcode));
187 }
188
189 void xbt_os_mutex_unlock(xbt_os_mutex_t mutex) {
190    int errcode;
191    
192    if ((errcode=pthread_mutex_unlock(&(mutex->m))))
193      THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s",
194             mutex, strerror(errcode));
195 }
196
197 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
198    int errcode;
199    
200    if (!mutex) return;
201    
202    if ((errcode=pthread_mutex_destroy(&(mutex->m))))
203      THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s",
204             mutex, strerror(errcode));
205    free(mutex);
206 }
207
208 /***** condition related functions *****/
209 typedef struct xbt_os_cond_ {
210   /* KEEP IT IN SYNC WITH xbt_thread.c */
211    pthread_cond_t c;
212 } s_xbt_os_cond_t;
213
214 xbt_os_cond_t xbt_os_cond_init(void) {
215    xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t,1);
216    int errcode;
217    if ((errcode=pthread_cond_init(&(res->c),NULL)))
218      THROW1(system_error,errcode,"pthread_cond_init() failed: %s",
219             strerror(errcode));
220
221    return res;
222 }
223
224 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
225    int errcode;
226    if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m))))
227      THROW3(system_error,errcode,"pthread_cond_wait(%p,%p) failed: %s",
228             cond,mutex, strerror(errcode));
229 }
230
231 #include <time.h>
232 #include <math.h>
233 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
234    int errcode;
235    struct timespec ts_end;
236    double end = delay + xbt_os_time();
237    ts_end.tv_sec = (time_t) floor(end);
238    ts_end.tv_nsec = (long)  ( ( end - ts_end.tv_sec) * 1000000000);
239    DEBUG3("pthread_cond_timedwait(%p,%p,%p)",&(cond->c),&(mutex->m), &ts_end);
240    switch ( (errcode=pthread_cond_timedwait(&(cond->c),&(mutex->m), &ts_end)) ) {
241     case ETIMEDOUT:
242      THROW3(timeout_error,errcode,"condition %p (mutex %p) wasn't signaled before timeout (%f)",
243             cond,mutex, delay);
244     default:
245      THROW4(system_error,errcode,"pthread_cond_timedwait(%p,%p,%f) failed: %s",
246             cond,mutex, delay, strerror(errcode));
247    }   
248 }
249
250 void xbt_os_cond_signal(xbt_os_cond_t cond) {
251    int errcode;
252    if ((errcode=pthread_cond_signal(&(cond->c))))
253      THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s",
254             cond, strerror(errcode));
255 }
256          
257 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
258    int errcode;
259    if ((errcode=pthread_cond_broadcast(&(cond->c))))
260      THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s",
261             cond, strerror(errcode));
262 }
263 void xbt_os_cond_destroy(xbt_os_cond_t cond){
264    int errcode;
265
266    if (!cond) return;
267
268    if ((errcode=pthread_cond_destroy(&(cond->c))))
269      THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s",
270             cond, strerror(errcode));
271    free(cond);
272 }
273
274 void *xbt_os_thread_getparam(void) {
275    xbt_os_thread_t t = xbt_os_thread_self();
276    return t?t->param:NULL;
277 }
278
279 /* ********************************* WINDOWS IMPLEMENTATION ************************************ */
280
281 #elif defined(WIN32)
282
283 typedef struct xbt_os_thread_ {
284   char *name;
285   HANDLE handle;                  /* the win thread handle        */
286   unsigned long id;               /* the win thread id            */
287   pvoid_f_pvoid_t *start_routine;
288   void* param;
289 } s_xbt_os_thread_t ;
290
291 /* key to the TLS containing the xbt_os_thread_t structure */
292 static unsigned long xbt_self_thread_key;
293
294 void xbt_os_thread_mod_init(void) {
295    xbt_self_thread_key = TlsAlloc();
296 }
297 void xbt_os_thread_mod_exit(void) {
298    
299    if (!TlsFree(xbt_self_thread_key)) 
300      THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule");
301 }
302
303 static DWORD WINAPI  wrapper_start_routine(void *s) {
304   xbt_os_thread_t t = (xbt_os_thread_t)s;
305  
306     if(!TlsSetValue(xbt_self_thread_key,t))
307      THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed");
308    
309    return (DWORD)t->start_routine(t->param);
310 }
311
312
313 xbt_os_thread_t xbt_os_thread_create(const char *name,pvoid_f_pvoid_t start_routine,
314                                void* param)  {
315    
316    xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1);
317
318    t->name = xbt_strdup(name);
319    t->start_routine = start_routine ;
320    t->param = param;
321    
322    t->handle = CreateThread(NULL,0,
323                             (LPTHREAD_START_ROUTINE)wrapper_start_routine,
324                             t,0,&(t->id));
325         
326    if(!t->handle) {
327      xbt_free(t);
328      THROW0(system_error,(int)GetLastError(),"CreateThread failed");
329    }
330    
331    return t;
332 }
333
334 const char* xbt_os_thread_name(xbt_os_thread_t t) {
335    return t->name;
336 }
337
338 const char* xbt_os_thread_self_name(void) {
339    xbt_os_thread_t t = xbt_os_thread_self();
340    return t?t->name:"main";
341 }
342
343 void 
344 xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) {
345
346         if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE))  
347                 THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed");
348                 
349         if(thread_return){
350                 
351                 if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return)))
352                         THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed");
353         }
354         
355         CloseHandle(thread->handle);
356         free(thread->name);
357         free(thread);
358 }
359
360 void xbt_os_thread_exit(int *retval) {
361    if(retval)
362         ExitThread(*retval);
363    else
364         ExitThread(0);
365 }
366
367 xbt_os_thread_t xbt_os_thread_self(void) {
368    return TlsGetValue(xbt_self_thread_key);
369 }
370
371 void *xbt_os_thread_getparam(void) {
372    xbt_os_thread_t t = xbt_os_thread_self();
373    return t->param;
374 }
375
376
377 void xbt_os_thread_yield(void) {
378     Sleep(0);
379 }
380 void xbt_os_thread_cancel(xbt_os_thread_t t) {
381    THROW_UNIMPLEMENTED;
382 }
383
384 /****** mutex related functions ******/
385 typedef struct xbt_os_mutex_ {
386   /* KEEP IT IN SYNC WITH xbt_thread.c */
387    CRITICAL_SECTION lock;   
388 } s_xbt_os_mutex_t;
389
390 xbt_os_mutex_t xbt_os_mutex_init(void) {
391    xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1);
392
393    /* initialize the critical section object */
394    InitializeCriticalSection(&(res->lock));
395    
396    return res;
397 }
398
399 void xbt_os_mutex_lock(xbt_os_mutex_t mutex) {
400
401    EnterCriticalSection(& mutex->lock);
402 }
403
404 void xbt_os_mutex_unlock(xbt_os_mutex_t mutex) {
405
406    LeaveCriticalSection (& mutex->lock);
407
408 }
409
410 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) {
411
412    if (!mutex) return;
413    
414    DeleteCriticalSection(& mutex->lock);                
415    free(mutex);
416 }
417
418 /***** condition related functions *****/
419  enum { /* KEEP IT IN SYNC WITH xbt_thread.c */
420     SIGNAL = 0,
421     BROADCAST = 1,
422     MAX_EVENTS = 2
423  };
424
425 typedef struct xbt_os_cond_ {
426   /* KEEP IT IN SYNC WITH xbt_thread.c */
427    HANDLE events[MAX_EVENTS];
428    
429    unsigned int waiters_count;           /* the number of waiters                        */
430    CRITICAL_SECTION waiters_count_lock;  /* protect access to waiters_count  */
431 } s_xbt_os_cond_t;
432
433 xbt_os_cond_t xbt_os_cond_init(void) {
434
435    xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1);
436         
437    memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION));
438         
439    /* initialize the critical section object */
440    InitializeCriticalSection(& res->waiters_count_lock);
441         
442    res->waiters_count = 0;
443         
444    /* Create an auto-reset event */
445    res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); 
446         
447    if(!res->events[SIGNAL]){
448       DeleteCriticalSection(& res->waiters_count_lock);
449       free(res);
450       THROW0(system_error,0,"CreateEvent failed for the signals");
451    }
452         
453    /* Create a manual-reset event. */
454    res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL);
455         
456    if(!res->events[BROADCAST]){
457                 
458       DeleteCriticalSection(& res->waiters_count_lock);         
459       CloseHandle(res->events[SIGNAL]);
460       free(res); 
461       THROW0(system_error,0,"CreateEvent failed for the broadcasts");
462    }
463
464    return res;
465 }
466
467 void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) {
468         
469    unsigned long wait_result;
470    int is_last_waiter;
471
472    /* lock the threads counter and increment it */
473    EnterCriticalSection (& cond->waiters_count_lock);
474    cond->waiters_count++;
475    LeaveCriticalSection (& cond->waiters_count_lock);
476                 
477    /* unlock the mutex associate with the condition */
478    LeaveCriticalSection (& mutex->lock);
479         
480    /* wait for a signal (broadcast or no) */
481    wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE);
482         
483    if(wait_result == WAIT_FAILED)
484      THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition");
485         
486    /* we have a signal lock the condition */
487    EnterCriticalSection (& cond->waiters_count_lock);
488    cond->waiters_count--;
489         
490    /* it's the last waiter or it's a broadcast ? */
491    is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0));
492         
493    LeaveCriticalSection (& cond->waiters_count_lock);
494         
495    /* yes it's the last waiter or it's a broadcast
496     * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function
497     * by the system. 
498     */
499    if (is_last_waiter)
500       if(!ResetEvent (cond->events[BROADCAST]))
501         THROW0(system_error,0,"ResetEvent failed");
502         
503    /* relock the mutex associated with the condition in accordance with the posix thread specification */
504    EnterCriticalSection (& mutex->lock);
505 }
506 void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) {
507    THROW_UNIMPLEMENTED;
508 }
509
510 void xbt_os_cond_signal(xbt_os_cond_t cond) {
511    int have_waiters;
512
513    EnterCriticalSection (& cond->waiters_count_lock);
514    have_waiters = cond->waiters_count > 0;
515    LeaveCriticalSection (& cond->waiters_count_lock);
516         
517    if (have_waiters)
518      if(!SetEvent(cond->events[SIGNAL]))
519        THROW0(system_error,0,"SetEvent failed");
520        
521    xbt_os_thread_yield();
522 }
523
524 void xbt_os_cond_broadcast(xbt_os_cond_t cond){
525    int have_waiters;
526
527    EnterCriticalSection (& cond->waiters_count_lock);
528    have_waiters = cond->waiters_count > 0;
529    LeaveCriticalSection (& cond->waiters_count_lock);
530         
531    if (have_waiters)
532      SetEvent(cond->events[BROADCAST]);
533 }
534
535 void xbt_os_cond_destroy(xbt_os_cond_t cond){
536    int error = 0;
537    
538    if (!cond) return;
539    
540    if(!CloseHandle(cond->events[SIGNAL]))
541      error = 1;
542         
543    if(!CloseHandle(cond->events[BROADCAST]))
544      error = 1;
545         
546    DeleteCriticalSection(& cond->waiters_count_lock);
547         
548    xbt_free(cond);
549    
550    if (error)
551      THROW0(system_error,0,"Error while destroying the condition");
552 }
553
554 #endif