Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
C version of exec-waitany
[simgrid.git] / examples / c / exec-waitany / exec-waitany.c
1 /* Copyright (c) 2019-2020. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "simgrid/actor.h"
7 #include "simgrid/engine.h"
8 #include "simgrid/exec.h"
9 #include "simgrid/host.h"
10
11 #include "xbt/asserts.h"
12 #include "xbt/log.h"
13
14 XBT_LOG_NEW_DEFAULT_CATEGORY(exec_waitany, "Messages specific for this example");
15
16 static void worker(int argc, char* argv[])
17 {
18   int with_timeout = !strcmp(argv[1], "true");
19
20   /* Vector in which we store all pending executions*/
21   sg_exec_t* pending_execs = malloc(sizeof(sg_exec_t) * 3);
22   int pending_execs_count  = 0;
23
24   for (int i = 0; i < 3; i++) {
25     char* name    = bprintf("Exec-%d", i);
26     double amount = (6 * (i % 2) + i + 1) * sg_host_speed(sg_host_self());
27
28     sg_exec_t exec = sg_actor_exec_init(amount);
29     sg_exec_set_name(exec, name);
30     pending_execs[pending_execs_count++] = exec;
31     sg_exec_start(exec);
32
33     XBT_INFO("Activity %s has started for %.0f seconds", name, amount / sg_host_speed(sg_host_self()));
34     free(name);
35   }
36
37   /* Now that executions were initiated, wait for their completion, in order of termination.
38    *
39    * This loop waits for first terminating execution with wait_any() and remove it with erase(), until all execs are
40    * terminated.
41    */
42   while (pending_execs_count > 0) {
43     int pos;
44     if (with_timeout)
45       pos = sg_exec_wait_any_for(pending_execs, pending_execs_count, 4);
46     else
47       pos = sg_exec_wait_any(pending_execs, pending_execs_count);
48
49     if (pos < 0) {
50       XBT_INFO("Do not wait any longer for an activity");
51       pending_execs_count = 0;
52     } else {
53       XBT_INFO("Activity at position %d is complete", pos);
54       memmove(pending_execs + pos, pending_execs + pos + 1, sizeof(sg_exec_t) * (pending_execs_count - pos - 1));
55       pending_execs_count--;
56     }
57     XBT_INFO("%d activities remain pending", pending_execs_count);
58   }
59
60   free(pending_execs);
61 }
62
63 int main(int argc, char* argv[])
64 {
65   simgrid_init(&argc, argv);
66   simgrid_load_platform(argv[1]);
67
68   const char* worker_argv[] = {"worker", "false"};
69   sg_actor_create("worker", sg_host_by_name("Tremblay"), worker, 2, worker_argv);
70
71   worker_argv[1] = "true";
72   sg_actor_create("worker_timeout", sg_host_by_name("Tremblay"), worker, 2, worker_argv);
73
74   simgrid_run();
75   return 0;
76 }