Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
52e2595aa23508d1bb58b90b0768c319477870e4
[simgrid.git] / examples / cpp / synchro-mutex / s4u-synchro-mutex.cpp
1 /* Copyright (c) 2006-2022. 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" /* All of S4U */
7 #include "xbt/config.hpp"
8 #include <mutex> /* std::mutex and std::lock_guard */
9
10 namespace sg4 = simgrid::s4u;
11
12 static simgrid::config::Flag<int> cfg_actor_count("actors", "How many pairs of actors should be started?", 6);
13
14 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
15
16 /* This worker uses a classical mutex */
17 static void worker(sg4::MutexPtr mutex, int& result)
18 {
19   // lock the mutex before enter in the critical section
20   mutex->lock();
21
22   XBT_INFO("Hello s4u, I'm ready to compute after a regular lock");
23   // And finally add it to the results
24   result += 1;
25   XBT_INFO("I'm done, good bye");
26
27   // You have to unlock the mutex if you locked it manually.
28   // Beware of exceptions preventing your unlock() from being executed!
29   mutex->unlock();
30 }
31
32 static void workerLockGuard(sg4::MutexPtr mutex, int& result)
33 {
34   // Simply use the std::lock_guard like this
35   // It's like a lock() that would do the unlock() automatically when getting out of scope
36   std::lock_guard<sg4::Mutex> lock(*mutex);
37
38   // then you are in a safe zone
39   XBT_INFO("Hello s4u, I'm ready to compute after a lock_guard");
40   // update the results
41   result += 1;
42   XBT_INFO("I'm done, good bye");
43
44   // Nothing specific here: the unlock will be automatic
45 }
46
47 static void master()
48 {
49   /* Create the requested amount of actors pairs. Each pair has a specific mutex and cell in `result`. */
50   int result[cfg_actor_count.get()];
51
52   for (int i = 0; i < cfg_actor_count; i++) {
53     result[i]           = 0;
54     sg4::MutexPtr mutex = sg4::Mutex::create();
55     sg4::Actor::create("worker", sg4::Host::by_name("Jupiter"), workerLockGuard, mutex, std::ref(result[i]));
56     sg4::Actor::create("worker", sg4::Host::by_name("Tremblay"), worker, mutex, std::ref(result[i]));
57   }
58
59   sg4::this_actor::sleep_for(10);
60   for (int i = 0; i < cfg_actor_count; i++)
61     XBT_INFO("Result[%d] -> %d", i, result[i]);
62 }
63
64 int main(int argc, char **argv)
65 {
66   sg4::Engine e(&argc, argv);
67   e.load_platform("../../platforms/two_hosts.xml");
68   sg4::Actor::create("main", e.host_by_name("Tremblay"), master);
69   e.run();
70
71   return 0;
72 }