Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[simgrid.git] / examples / c / exec-waitany / exec-waitany.c
1 /* Copyright (c) 2019-2021. 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   xbt_assert(argc > 1);
19   int with_timeout = !strcmp(argv[1], "true");
20
21   /* Vector in which we store all pending executions*/
22   sg_exec_t* pending_execs = xbt_malloc(sizeof(sg_exec_t) * 3);
23   int pending_execs_count  = 0;
24
25   for (int i = 0; i < 3; i++) {
26     char* name    = bprintf("Exec-%d", i);
27     double amount = (6 * (i % 2) + i + 1) * sg_host_get_speed(sg_host_self());
28
29     sg_exec_t exec = sg_actor_exec_init(amount);
30     sg_exec_set_name(exec, name);
31     pending_execs[pending_execs_count++] = exec;
32     sg_exec_start(exec);
33
34     XBT_INFO("Activity %s has started for %.0f seconds", name, amount / sg_host_get_speed(sg_host_self()));
35     free(name);
36   }
37
38   /* Now that executions were initiated, wait for their completion, in order of termination.
39    *
40    * This loop waits for first terminating execution with wait_any() and remove it with erase(), until all execs are
41    * terminated.
42    */
43   while (pending_execs_count > 0) {
44     int pos;
45     if (with_timeout)
46       pos = sg_exec_wait_any_for(pending_execs, pending_execs_count, 4);
47     else
48       pos = sg_exec_wait_any(pending_execs, pending_execs_count);
49
50     if (pos < 0) {
51       XBT_INFO("Do not wait any longer for an activity");
52       pending_execs_count = 0;
53     } else {
54       XBT_INFO("Activity at position %d is complete", pos);
55       memmove(pending_execs + pos, pending_execs + pos + 1, sizeof(sg_exec_t) * (pending_execs_count - pos - 1));
56       pending_execs_count--;
57     }
58     XBT_INFO("%d activities remain pending", pending_execs_count);
59   }
60
61   free(pending_execs);
62 }
63
64 int main(int argc, char* argv[])
65 {
66   simgrid_init(&argc, argv);
67   simgrid_load_platform(argv[1]);
68
69   const char* worker_argv[] = {"worker", "false"};
70   sg_actor_create("worker", sg_host_by_name("Tremblay"), worker, 2, worker_argv);
71
72   worker_argv[1] = "true";
73   sg_actor_create("worker_timeout", sg_host_by_name("Tremblay"), worker, 2, worker_argv);
74
75   simgrid_run();
76   return 0;
77 }