Logo AND Algorithmique Numérique Distribuée

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