Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
name threads, plus only put an exeption fetcher and handler when using contextes...
[simgrid.git] / src / xbt / context.c
1 /*      $Id$     */
2
3 /* a fast and simple context switching library                              */
4
5 /* Copyright (c) 2004 Arnaud Legrand.                                       */
6 /* Copyright (c) 2004, 2005 Martin Quinson.                                 */
7 /* All rights reserved.                                                     */
8
9 /* This program is free software; you can redistribute it and/or modify it
10  * under the terms of the license (GNU LGPL) which comes with this package. */
11
12 #include "portable.h"
13 #include "context_private.h"
14 #include "xbt/log.h"
15 #include "xbt/dynar.h"
16 #include "xbt/xbt_os_thread.h"
17 #include "xbt/ex_interface.h"
18
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ctx, xbt, "Context");
20
21 #define VOIRP(expr) DEBUG1("  {" #expr " = %p }", expr)
22
23 static xbt_context_t current_context = NULL;
24 static xbt_context_t init_context = NULL;
25 static xbt_swag_t context_to_destroy = NULL;
26 static xbt_swag_t context_living = NULL;
27 #ifdef CONTEXT_THREADS
28 static xbt_os_mutex_t creation_mutex;
29 static xbt_os_cond_t creation_cond;
30 #endif
31
32 static void __context_exit(xbt_context_t context, int value);
33 static void __xbt_context_yield(xbt_context_t context)
34 {
35   xbt_assert0(current_context, "You have to call context_init() first.");
36
37   DEBUG2
38       ("--------- current_context (%p) is yielding to context(%p) ---------",
39        current_context, context);
40
41 #ifdef CONTEXT_THREADS
42   if (context) {
43     xbt_context_t self = current_context;
44     DEBUG2("[%p] **** Locking ctx %p ****", self, context);
45     xbt_os_mutex_lock(context->mutex);
46     DEBUG1("[%p] **** Updating current_context ****", self);
47     current_context = context;
48     DEBUG1("[%p] **** Releasing the prisonner ****", self);
49     xbt_os_cond_signal(context->cond);
50     DEBUG3("[%p] **** Going to jail on individual %p/%p ****", self,
51            context->cond, context->mutex);
52     xbt_os_cond_wait(context->cond, context->mutex);
53     DEBUG2("[%p] **** Unlocking individual %p ****", self, context->mutex);
54     xbt_os_mutex_unlock(context->mutex);
55     DEBUG1("[%p] **** Updating current_context ****", self);
56     current_context = self;
57   }
58 #else                           /* use SUSv2 contexts */
59   VOIRP(current_context);
60   if (current_context)
61     VOIRP(current_context->save);
62
63   VOIRP(context);
64
65   if (context)
66     VOIRP(context->save);
67
68   if (context) {
69
70     int return_value = 0;
71
72     if (context->save == NULL) {
73
74       DEBUG1("[%p] **** Yielding to somebody else ****", current_context);
75       DEBUG2("Saving current_context value (%p) to context(%p)->save",
76              current_context, context);
77       context->save = current_context;
78       DEBUG1("current_context becomes  context(%p) ", context);
79       current_context = context;
80       DEBUG1
81           ("Current position memorized (context->save). Jumping to context (%p)",
82            context);
83       return_value = swapcontext(&(context->save->uc), &(context->uc));
84       xbt_assert0((return_value == 0), "Context swapping failure");
85       DEBUG1("I am (%p). Coming back\n", context);
86     } else {
87       xbt_context_t old_context = context->save;
88       DEBUG1("[%p] **** Back ! ****", context);
89       DEBUG2("Setting current_context (%p) to context(%p)->save",
90              current_context, context);
91       current_context = context->save;
92       DEBUG1("Setting context(%p)->save to NULL", context);
93       context->save = NULL;
94       DEBUG2("Current position memorized (%p). Jumping to context (%p)",
95              context, old_context);
96       return_value = swapcontext(&(context->uc), &(old_context->uc));
97       xbt_assert0((return_value == 0), "Context swapping failure");
98       DEBUG1("I am (%p). Coming back\n", context);
99
100     }
101   }
102 #endif
103   if (current_context->iwannadie)
104     __context_exit(current_context, 1);
105
106   return;
107 }
108
109 static void xbt_context_free(xbt_context_t context)
110 {
111   if (!context)
112     return;
113   DEBUG1("Freeing %p", context);
114   free(context->name);
115 #ifdef CONTEXT_THREADS
116   /*DEBUG1("\t joining %p",(void *)context->thread->t); */
117   DEBUG1("\t joining %p", (void *) context->thread);
118
119   xbt_os_thread_join(context->thread, NULL);
120
121   DEBUG1("\t mutex_destroy %p", (void *) context->mutex);
122   xbt_os_mutex_destroy(context->mutex);
123   DEBUG1("\t cond_destroy %p", (void *) context->cond);
124   xbt_os_cond_destroy(context->cond);
125
126   context->thread = NULL;
127   context->mutex = NULL;
128   context->cond = NULL;
129 #else
130   if (context->exception)
131     free(context->exception);
132 #endif
133    
134   free(context);
135   return;
136 }
137
138 static void __context_exit(xbt_context_t context, int value)
139 {
140   int i;
141
142   DEBUG1("--------- %p is exiting ---------", context);
143
144   DEBUG0("Calling cleanup functions");
145   if (context->cleanup_func) {
146     DEBUG0("Calling cleanup function");
147     context->cleanup_func(context->cleanup_arg);
148   }
149
150   DEBUG0("Freeing arguments");
151   for (i = 0; i < context->argc; i++)
152     if (context->argv[i])
153       free(context->argv[i]);
154
155   if (context->argv)
156     free(context->argv);
157
158   DEBUG0("Putting context in the to_destroy set");
159   xbt_swag_remove(context, context_living);
160   xbt_swag_insert(context, context_to_destroy);
161   DEBUG0("Context put in the to_destroy set");
162
163   DEBUG0("Yielding");
164
165 #ifdef CONTEXT_THREADS
166   DEBUG2("[%p] **** Locking %p ****", context, context->mutex);
167   xbt_os_mutex_lock(context->mutex);
168 /*      DEBUG1("[%p] **** Updating current_context ****"); */
169 /*      current_context = context; */
170   DEBUG1("[%p] **** Releasing the prisonner ****", context);
171   xbt_os_cond_signal(context->cond);
172   DEBUG2("[%p] **** Unlocking individual %p ****", context,
173          context->mutex);
174   xbt_os_mutex_unlock(context->mutex);
175   DEBUG1("[%p] **** Exiting ****", context);
176   xbt_os_thread_exit(NULL);     // We should provide return value in case other wants it
177 #else
178   __xbt_context_yield(context);
179 #endif
180   xbt_assert0(0, "You can't be here!");
181 }
182
183 static void *__context_wrapper(void *c)
184 {
185   xbt_context_t context = current_context;
186
187 #ifdef CONTEXT_THREADS
188   context = (xbt_context_t) c;
189   context->thread = xbt_os_thread_self();
190
191   DEBUG3("**[ctx:%p;self:%p]** Lock creation_mutex %p ****", context,
192          (void *) xbt_os_thread_self(), creation_mutex);
193   xbt_os_mutex_lock(creation_mutex);
194   xbt_os_mutex_lock(context->mutex);
195
196   DEBUG4
197       ("**[ctx:%p;self:%p]** Releasing the creator (creation_cond %p,%p) ****",
198        context, (void *) xbt_os_thread_self(), creation_cond,
199        creation_mutex);
200   xbt_os_cond_signal(creation_cond);
201   xbt_os_mutex_unlock(creation_mutex);
202
203   DEBUG4("**[ctx:%p;self:%p]** Going to Jail on lock %p and cond %p ****",
204          context, (void *) xbt_os_thread_self(), context->mutex,
205          context->cond);
206   xbt_os_cond_wait(context->cond, context->mutex);
207
208   DEBUG3("**[ctx:%p;self:%p]** Unlocking individual %p ****",
209          context, (void *) xbt_os_thread_self(), context->mutex);
210   xbt_os_mutex_unlock(context->mutex);
211
212 #endif
213
214   if (context->startup_func)
215     context->startup_func(context->startup_arg);
216
217   DEBUG0("Calling the main function");
218
219   __context_exit(context, (context->code) (context->argc, context->argv));
220   return NULL;
221 }
222
223 #ifndef CONTEXT_THREADS
224 /* callback: context fetching (used only with ucontext, os_thread deal with it for us otherwise) */
225 static ex_ctx_t *_context_ex_ctx(void) {
226   return current_context->exception;
227 }
228
229 /* callback: termination */
230 static void _context_ex_terminate(xbt_ex_t * e) {
231   xbt_ex_display(e);
232
233   abort();
234   /* FIXME: there should be a configuration variable to 
235      choose to kill everyone or only this one */
236 }
237 #endif 
238
239 /** \name Functions 
240  *  \ingroup XBT_context
241  */
242 /* @{ */
243 /** Context module initialization
244  *
245  * \warning It has to be called before using any other function of this module.
246  */
247 void xbt_context_init(void)
248 {
249   if (!current_context) {
250     current_context = init_context = xbt_new0(s_xbt_context_t, 1);
251     DEBUG1("Init Context (%p)", init_context);
252
253     init_context->iwannadie = 0; /* useless but makes valgrind happy */
254     context_to_destroy =
255         xbt_swag_new(xbt_swag_offset(*current_context, hookup));
256     context_living =
257         xbt_swag_new(xbt_swag_offset(*current_context, hookup));
258     xbt_swag_insert(init_context, context_living);
259 #ifdef CONTEXT_THREADS
260     creation_mutex = xbt_os_mutex_init();
261     creation_cond = xbt_os_cond_init();
262 #else
263     init_context->exception = xbt_new(ex_ctx_t, 1);
264     XBT_CTX_INITIALIZE(init_context->exception);
265     __xbt_ex_ctx = _context_ex_ctx;
266     __xbt_ex_terminate = _context_ex_terminate;
267 #endif
268   }
269 }
270
271 /** Garbage collection
272  *
273  * Should be called some time to time to free the memory allocated for contexts
274  * that have finished executing their main functions.
275  */
276 void xbt_context_empty_trash(void)
277 {
278   xbt_context_t context = NULL;
279   DEBUG1("Emptying trashbin (%d contexts to free)",
280          xbt_swag_size(context_to_destroy));
281   while ((context = xbt_swag_extract(context_to_destroy)))
282     xbt_context_free(context);
283 }
284
285 /** 
286  * \param context the context to start
287  * 
288  * Calling this function prepares \a context to be run. It will 
289    however run effectively only when calling #xbt_context_schedule
290  */
291 void xbt_context_start(xbt_context_t context)
292 {
293 #ifdef CONTEXT_THREADS
294   /* Launch the thread */
295    
296   DEBUG3("**[ctx:%p;self:%p]** Locking creation_mutex %p ****", context,
297          xbt_os_thread_self(), creation_mutex);
298   xbt_os_mutex_lock(creation_mutex);
299
300   DEBUG2("**[ctx:%p;self:%p]** Thread create ****", context,
301          xbt_os_thread_self());
302   context->thread = xbt_os_thread_create(context->name,__context_wrapper, context);
303   DEBUG3("**[ctx:%p;self:%p]** Thread created : %p ****", context,
304          xbt_os_thread_self(), context->thread);
305
306   DEBUG4
307       ("**[ctx:%p;self:%p]** Going to jail on creation_cond/mutex (%p,%p) ****",
308        context, xbt_os_thread_self(), creation_cond, creation_mutex);
309   xbt_os_cond_wait(creation_cond, creation_mutex);
310   DEBUG3("**[ctx:%p;self:%p]** Unlocking creation %p ****", context,
311          xbt_os_thread_self(), creation_mutex);
312   xbt_os_mutex_unlock(creation_mutex);
313 #else
314   makecontext(&(context->uc), (void (*)(void)) __context_wrapper, 1,
315               context);
316 #endif
317   return;
318 }
319
320 /** 
321  * \param code a main function
322  * \param startup_func a function to call when running the context for
323  *      the first time and just before the main function \a code
324  * \param startup_arg the argument passed to the previous function (\a startup_func)
325  * \param cleanup_func a function to call when running the context, just after 
326         the termination of the main function \a code
327  * \param cleanup_arg the argument passed to the previous function (\a cleanup_func)
328  * \param argc first argument of function \a code
329  * \param argv seconde argument of function \a code
330  */
331 xbt_context_t xbt_context_new(const char *name,xbt_main_func_t code,
332                               void_f_pvoid_t startup_func,
333                               void *startup_arg,
334                               void_f_pvoid_t cleanup_func,
335                               void *cleanup_arg, int argc, char *argv[])
336 {
337   xbt_context_t res = NULL;
338
339   res = xbt_new0(s_xbt_context_t, 1);
340
341   res->code = code;
342   res->name = xbt_strdup(name);
343 #ifdef CONTEXT_THREADS
344   res->mutex = xbt_os_mutex_init();
345   res->cond = xbt_os_cond_init();
346 #else
347
348   xbt_assert2(getcontext(&(res->uc)) == 0,
349               "Error in context saving: %d (%s)", errno, strerror(errno));
350   res->uc.uc_link = NULL;
351   /*   res->uc.uc_link = &(current_context->uc); */
352   /* WARNING : when this context is over, the current_context (i.e. the 
353      father), is awaken... Theorically, the wrapper should prevent using 
354      this feature. */
355   res->uc.uc_stack.ss_sp = pth_skaddr_makecontext(res->stack, STACK_SIZE);
356   res->uc.uc_stack.ss_size =
357       pth_sksize_makecontext(res->stack, STACK_SIZE);
358    
359   res->exception = xbt_new(ex_ctx_t, 1);
360   XBT_CTX_INITIALIZE(res->exception);
361 #endif                          /* CONTEXT_THREADS or not */
362
363   res->iwannadie = 0; /* useless but makes valgrind happy */
364
365   res->argc = argc;
366   res->argv = argv;
367   res->startup_func = startup_func;
368   res->startup_arg = startup_arg;
369   res->cleanup_func = cleanup_func;
370   res->cleanup_arg = cleanup_arg;
371
372   xbt_swag_insert(res, context_living);
373
374   return res;
375 }
376
377 /** 
378  * Calling this function makes the current context yield. The context
379  * that scheduled it returns from xbt_context_schedule as if nothing
380  * had happened.
381  */
382 void xbt_context_yield(void)
383 {
384   __xbt_context_yield(current_context);
385 }
386
387 /** 
388  * \param context the winner
389  *
390  * Calling this function blocks the current context and schedule \a context.  
391  * When \a context will call xbt_context_yield, it will return
392  * to this function as if nothing had happened.
393  */
394 void xbt_context_schedule(xbt_context_t context)
395 {
396   DEBUG1("Scheduling %p", context);
397   xbt_assert0((current_context == init_context),
398               "You are not supposed to run this function here!");
399   __xbt_context_yield(context);
400 }
401
402 /** 
403  * This function kill all existing context and free all the memory
404  * that has been allocated in this module.
405  */
406 void xbt_context_exit(void)
407 {
408   xbt_context_t context = NULL;
409
410   xbt_context_empty_trash();
411   while ((context = xbt_swag_extract(context_living))) {
412     if (context != init_context) {
413       xbt_context_kill(context);
414     }
415   }
416 #ifdef CONTEXT_THREADS
417   xbt_os_mutex_destroy(creation_mutex);
418   xbt_os_cond_destroy(creation_cond);
419 #else   
420   free(init_context->exception);
421 #endif
422   free(init_context);
423   init_context = current_context = NULL;
424
425   xbt_context_empty_trash();
426   xbt_swag_free(context_to_destroy);
427   xbt_swag_free(context_living);
428
429 }
430
431 /** 
432  * \param context poor victim
433  *
434  * This function simply kills \a context... scarry isn't it ?
435  */
436 void xbt_context_kill(xbt_context_t context)
437 {
438   DEBUG1("Killing %p", context);
439
440   context->iwannadie = 1;
441   DEBUG1("Scheduling %p", context);
442   __xbt_context_yield(context);
443   DEBUG1("End of Scheduling %p", context);
444
445   return;
446 }
447
448 /* @} */
449
450 /* Stub of the stuff to interact with JAVA threads; not used in native lib */
451 void xbt_context_set_jprocess(xbt_context_t context, void *jp)
452 {
453 }
454 void *xbt_context_get_jprocess(xbt_context_t context)
455 {
456   return NULL;
457 }
458
459 void xbt_context_set_jmutex(xbt_context_t context, void *jm)
460 {
461 }
462 void *xbt_context_get_jmutex(xbt_context_t context)
463 {
464   return NULL;
465 }
466
467 void xbt_context_set_jcond(xbt_context_t context, void *jc)
468 {
469 }
470 void *xbt_context_get_jcond(xbt_context_t context)
471 {
472   return NULL;
473 }
474
475 void xbt_context_set_jenv(xbt_context_t context, void *je)
476 {
477 }
478 void *xbt_context_get_jenv(xbt_context_t context)
479 {
480   return NULL;
481 }