1 /* Copyright (c) 2006-2022. The SimGrid Team. All rights reserved. */
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. */
6 #include "simgrid/s4u.hpp" /* All of S4U */
7 #include "simgrid/modelchecker.h" // This example is also used to test the modelchecker on mutexes
9 #include <mutex> /* std::mutex and std::lock_guard */
13 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
15 /* This worker uses a classical mutex */
16 static void worker(simgrid::s4u::MutexPtr mutex, int& result)
18 // lock the mutex before enter in the critical section
21 XBT_INFO("Hello s4u, I'm ready to compute after a regular lock");
22 // And finally add it to the results
24 XBT_INFO("I'm done, good bye");
26 // You have to unlock the mutex if you locked it manually.
27 // Beware of exceptions preventing your unlock() from being executed!
31 static void workerLockGuard(simgrid::s4u::MutexPtr mutex, int& result)
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);
37 // then you are in a safe zone
38 XBT_INFO("Hello s4u, I'm ready to compute after a lock_guard");
41 XBT_INFO("I'm done, good bye");
43 // Nothing specific here: the unlock will be automatic
49 simgrid::s4u::MutexPtr mutex = simgrid::s4u::Mutex::create();
51 for (int i = 0; i < NB_ACTOR * 2 ; i++) {
52 // To create a worker use the static method simgrid::s4u::Actor.
54 simgrid::s4u::Actor::create("worker", simgrid::s4u::Host::by_name("Jupiter"), workerLockGuard, mutex,
57 simgrid::s4u::Actor::create("worker", simgrid::s4u::Host::by_name("Tremblay"), worker, mutex, std::ref(result));
60 simgrid::s4u::this_actor::sleep_for(10);
61 XBT_INFO("Results is -> %d", result);
64 int main(int argc, char **argv)
66 simgrid::s4u::Engine e(&argc, argv);
68 if (MC_is_active()) // Reduce the size of that test when running in the model-checker
71 e.load_platform("../../platforms/two_hosts.xml");
72 simgrid::s4u::Actor::create("main", e.host_by_name("Tremblay"), master);