Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c7124a40f2ef9c61a9c5913962353fad1fabdbf2
[simgrid.git] / examples / c / synchro-semaphore / synchro-semaphore.c
1 /* Copyright (c) 2013-2022. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "simgrid/actor.h"
8 #include "simgrid/engine.h"
9 #include "simgrid/host.h"
10 #include "simgrid/semaphore.h"
11
12 #include "xbt/log.h"
13 #include "xbt/str.h"
14
15 XBT_LOG_NEW_DEFAULT_CATEGORY(semaphores, "Messages specific for this example");
16
17 sg_sem_t sem;
18
19 static void peer(int argc, char* argv[])
20 {
21   int i = 0;
22   while (i < argc) {
23     double wait_time = xbt_str_parse_double(argv[i], "Invalid wait time");
24     i++;
25     sg_actor_sleep_for(wait_time);
26     // cover the two cases: with and without timeout
27     if (i > 1) {
28       XBT_INFO("Trying for 1 sec to acquire #%d (that is %sfree)", i, sg_sem_would_block(sem) ? "not " : "");
29       while (sg_sem_acquire_timeout(sem, 1.)) {
30         XBT_INFO("Timeout.. Try #%d for another second.", i);
31       }
32     } else {
33       XBT_INFO("Acquire #%d (that is %sfree)", i, sg_sem_would_block(sem) ? "not " : "");
34       sg_sem_acquire(sem);
35     }
36     XBT_INFO("Acquired #%d", i);
37
38     wait_time = xbt_str_parse_double(argv[i], "Invalid wait time");
39     i++;
40     sg_actor_sleep_for(wait_time);
41     XBT_INFO("Releasing #%d", i);
42     sg_sem_release(sem);
43     XBT_INFO("Released #%d", i);
44   }
45   sg_actor_sleep_for(50);
46   XBT_INFO("Done");
47 }
48
49 int main(int argc, char* argv[])
50 {
51   simgrid_init(&argc, argv);
52   simgrid_load_platform(argv[1]);
53
54   sg_host_t h = sg_host_by_name("Fafard");
55
56   sem                      = sg_sem_init(1);
57   XBT_INFO("Semaphore initialized with capacity = %d", sg_sem_get_capacity(sem));
58   const char* aliceTimes[] = {"0", "1", "3", "5", "1", "2", "5", "0"};
59   const char* bobTimes[]   = {"0.9", "1", "1", "2", "2", "0", "0", "5"};
60
61   sg_actor_create_("Alice", h, peer, 8, aliceTimes);
62   sg_actor_create_("Bob", h, peer, 8, bobTimes);
63
64   simgrid_run();
65   sg_sem_destroy(sem);
66   XBT_INFO("Finished\n");
67   return 0;
68 }