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 "xbt/config.hpp"
8 namespace sg4 = simgrid::s4u;
10 #include <mutex> /* std::mutex and std::lock_guard */
12 static simgrid::config::Flag<int> cfg_actor_count("actors", "How many pairs of actors should be started?", 6);
14 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
16 /* This worker uses a classical mutex */
17 static void worker(sg4::MutexPtr mutex, int& result)
19 // lock the mutex before enter in the critical section
22 XBT_INFO("Hello s4u, I'm ready to compute after a regular lock");
23 // And finally add it to the results
25 XBT_INFO("I'm done, good bye");
27 // You have to unlock the mutex if you locked it manually.
28 // Beware of exceptions preventing your unlock() from being executed!
32 static void workerLockGuard(sg4::MutexPtr mutex, int& result)
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);
38 // then you are in a safe zone
39 XBT_INFO("Hello s4u, I'm ready to compute after a lock_guard");
42 XBT_INFO("I'm done, good bye");
44 // Nothing specific here: the unlock will be automatic
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));
57 sg4::this_actor::sleep_for(10);
58 XBT_INFO("Results is -> %d", result);
61 int main(int argc, char **argv)
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);