Logo AND Algorithmique Numérique Distribuée

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