1 /* xbt_synchro -- advanced multithreaded features */
2 /* Working on top of real threads in RL and of simulated processes in SG */
4 /* Copyright 2009 Da SimGrid Team. All right reserved. */
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. */
9 #include "xbt/sysdep.h"
10 #include "xbt/dynar.h"
11 #include "xbt/synchro.h"
16 void_f_int_pvoid_t function;
18 } s_worker_data_t,*worker_data_t;
20 static void worker_wait_n_free(void*w) {
21 worker_data_t worker=*(worker_data_t*)w;
22 xbt_thread_join(worker->worker);
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));
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);
35 /* Start all workers */
36 xbt_dynar_foreach(datas,cursor,data){
37 worker_data_t w = xbt_new0(s_worker_data_t,1);
39 w->function = function;
41 xbt_dynar_push(workers,&w);
42 w->worker = xbt_thread_create("dopar worker",worker_wrapper,w,1/*joinable*/);
45 xbt_dynar_free(&workers);
50 #include "xbt/synchro.h"
52 XBT_TEST_SUITE("synchro", "Advanced synchronization mecanisms");
53 XBT_LOG_EXTERNAL_CATEGORY(xbt_dyn);
54 XBT_LOG_DEFAULT_CATEGORY(xbt_dyn);
56 static void add100(int rank,void *data) {
57 //INFO2("Thread%d: Add 100 to %d",rank,*(int*)data);
61 XBT_TEST_UNIT("dopar", test_dynar_dopar, "do parallel on dynars of integers")
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));
73 xbt_dynar_dopar(d,add100);
75 xbt_dynar_foreach(d, cursor, i) {
76 xbt_test_assert2(i == cpt,
77 "The retrieved value is not the expected one (%d!=%d)",
84 #endif /* SIMGRID_TEST */