Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a17d574533aa3c21d10cc6fd16db43e122861fb8
[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 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 int main(int argc, char** argv)
48 {
49   sg4::Engine e(&argc, argv);
50   e.load_platform("../../platforms/two_hosts.xml");
51
52   /* Create the requested amount of actors pairs. Each pair has a specific mutex and cell in `result`. */
53   std::vector<int> result(cfg_actor_count.get());
54
55   for (int i = 0; i < cfg_actor_count; i++) {
56     sg4::MutexPtr mutex = sg4::Mutex::create();
57     sg4::Actor::create("worker", sg4::Host::by_name("Jupiter"), workerLockGuard, mutex, std::ref(result[i]));
58     sg4::Actor::create("worker", sg4::Host::by_name("Tremblay"), worker, mutex, std::ref(result[i]));
59   }
60
61   e.run();
62
63   for (int i = 0; i < cfg_actor_count; i++)
64     XBT_INFO("Result[%d] -> %d", i, result[i]);
65
66   return 0;
67 }