Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[examples] add s4u-synchro-semaphore
[simgrid.git] / examples / s4u / synchro-semaphore / s4u-synchro-semaphore.cpp
1 /* Copyright (c) 2006-2018. 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/s4u.hpp"
7
8 #include <memory>
9
10 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
11
12 // This example implements a one-time use barrier with 1 semaphore and 1 mutex.
13
14 static void worker(simgrid::s4u::SemaphorePtr semaphore, simgrid::s4u::MutexPtr mutex, int process_count, std::shared_ptr<int> count)
15 {
16   mutex->lock();
17   XBT_INFO("Got mutex. Incrementing count.");
18   XBT_INFO("Count is %d", *count);
19   *count = (*count) + 1;
20   XBT_INFO("Count is now %d. Process count is %d.", *count, process_count);
21
22   if (*count == process_count) {
23     XBT_INFO("Releasing the semaphore %d times.", process_count-1);
24     for (int i = 0; i < process_count-1; i++) {
25       semaphore->release();
26     }
27
28     XBT_INFO("Releasing mutex.");
29     mutex->unlock();
30   }
31   else {
32     XBT_INFO("Releasing mutex.");
33     mutex->unlock();
34     XBT_INFO("Acquiring semaphore.");
35     semaphore->acquire();
36   }
37
38   XBT_INFO("Bye!");
39 }
40
41 static void master(unsigned int process_count)
42 {
43   simgrid::s4u::SemaphorePtr semaphore = simgrid::s4u::Semaphore::create(0);
44   simgrid::s4u::MutexPtr mutex = simgrid::s4u::Mutex::create();
45   std::shared_ptr<int> count(new int);
46   *count = 0;
47
48   XBT_INFO("Spawning %d workers", process_count);
49   for (unsigned int i = 0; i < process_count; i++) {
50     simgrid::s4u::Actor::create("worker", simgrid::s4u::Host::by_name("Jupiter"), worker, semaphore, mutex, process_count, count);
51   }
52 }
53
54 int main(int argc, char **argv)
55 {
56   // Parameter: Number of processes in the barrier
57   xbt_assert(argc >= 2, "Usage: %s <process-count>\n", argv[0]);
58   unsigned int process_count = std::stoi(argv[1]);
59   xbt_assert(process_count > 0, "<process-count> must be greater than 0");
60
61   simgrid::s4u::Engine e(&argc, argv);
62   e.load_platform("../../platforms/two_hosts.xml");
63   simgrid::s4u::Actor::create("master", simgrid::s4u::Host::by_name("Tremblay"), master, process_count);
64   e.run();
65
66   return 0;
67 }