Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Change the prototype of xbt_thread_create(), sorry.
[simgrid.git] / src / xbt / xbt_synchro.c
1 /* xbt_synchro -- advanced multithreaded features                           */
2 /* Working on top of real threads in RL and of simulated processes in SG    */
3
4 /* Copyright 2009 Da SimGrid Team. All right reserved.                      */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "xbt/sysdep.h"
10 #include "xbt/dynar.h"
11 #include "xbt/synchro.h"
12
13 typedef struct {
14   xbt_dynar_t data;
15   int rank;
16   void_f_int_pvoid_t function;
17   xbt_thread_t worker;
18 } s_worker_data_t,*worker_data_t;
19
20 static void worker_wait_n_free(void*w) {
21   worker_data_t worker=*(worker_data_t*)w;
22   xbt_thread_join(worker->worker);
23   xbt_free(worker);
24 }
25 static void worker_wrapper(void *w) {
26   worker_data_t me=(worker_data_t)w;
27   (*me->function)(me->rank,xbt_dynar_get_ptr(me->data,me->rank));
28   xbt_thread_exit();
29 }
30
31 void xbt_dynar_dopar(xbt_dynar_t datas, void_f_int_pvoid_t function) {
32   xbt_dynar_t workers = xbt_dynar_new(sizeof(worker_data_t),worker_wait_n_free);
33   unsigned int cursor;
34   void *data;
35   /* Start all workers */
36   xbt_dynar_foreach(datas,cursor,data){
37     worker_data_t w = xbt_new0(s_worker_data_t,1);
38     w->data = datas;
39     w->function = function;
40     w->rank=cursor;
41     xbt_dynar_push(workers,&w);
42     w->worker = xbt_thread_create("dopar worker",worker_wrapper,w,1/*joinable*/);
43   }
44   /* wait them all */
45   xbt_dynar_free(&workers);
46 }
47
48 #ifdef SIMGRID_TEST
49 #define NB_ELEM 50
50 #include "xbt/synchro.h"
51
52 XBT_TEST_SUITE("synchro", "Advanced synchronization mecanisms");
53 XBT_LOG_EXTERNAL_CATEGORY(xbt_dyn);
54 XBT_LOG_DEFAULT_CATEGORY(xbt_dyn);
55
56 static void add100(int rank,void *data) {
57   //INFO2("Thread%d: Add 100 to %d",rank,*(int*)data);
58   *(int*)data +=100;
59 }
60
61 XBT_TEST_UNIT("dopar", test_dynar_dopar, "do parallel on dynars of integers")
62 {
63   xbt_dynar_t d;
64   int i, cpt;
65   unsigned int cursor;
66
67   xbt_test_add1("==== Push %d int, add 100 to each of them in parallel and check the results", NB_ELEM);
68   d = xbt_dynar_new(sizeof(int), NULL);
69   for (cpt = 0; cpt < NB_ELEM; cpt++) {
70     xbt_dynar_push_as(d, int, cpt);     /* This is faster (and possible only with scalars) */
71     xbt_test_log2("Push %d, length=%lu", cpt, xbt_dynar_length(d));
72   }
73   xbt_dynar_dopar(d,add100);
74   cpt = 100;
75   xbt_dynar_foreach(d, cursor, i) {
76     xbt_test_assert2(i == cpt,
77                      "The retrieved value is not the expected one (%d!=%d)",
78                      i, cpt);
79     cpt++;
80   }
81   xbt_dynar_free(&d);
82 }
83
84 #endif /* SIMGRID_TEST */
85
86