Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
9c7d4f6754360c5c77ddabc87a10b229a10bd5c1
[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 namespace sg4 = simgrid::s4u;
9
10 #include <mutex> /* std::mutex and std::lock_guard */
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   int result = 0;
50
51   for (int i = 0; i < cfg_actor_count; i++) {
52     sg4::MutexPtr mutex = sg4::Mutex::create();
53     sg4::Actor::create("worker", sg4::Host::by_name("Jupiter"), workerLockGuard, mutex, std::ref(result));
54     sg4::Actor::create("worker", sg4::Host::by_name("Tremblay"), worker, mutex, std::ref(result));
55   }
56
57   sg4::this_actor::sleep_for(10);
58   XBT_INFO("Results is -> %d", result);
59 }
60
61 int main(int argc, char **argv)
62 {
63   sg4::Engine e(&argc, argv);
64   e.load_platform("../../platforms/two_hosts.xml");
65   sg4::Actor::create("main", e.host_by_name("Tremblay"), master);
66   e.run();
67
68   return 0;
69 }