1 /* Copyright (c) 2006-2023. 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 #include <mutex> /* std::mutex and std::scoped_lock */
10 namespace sg4 = simgrid::s4u;
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 workerScopedLock(sg4::MutexPtr mutex, int& result)
34 // Simply use the std::scoped_lock like this
35 // It's like a lock() that would do the unlock() automatically when getting out of scope
36 const std::scoped_lock lock(*mutex);
38 // then you are in a safe zone
39 XBT_INFO("Hello s4u, I'm ready to compute after a scoped_lock");
42 XBT_INFO("I'm done, good bye");
44 // Nothing specific here: the unlock will be automatic
47 int main(int argc, char** argv)
49 sg4::Engine e(&argc, argv);
50 e.load_platform(argc > 1 ? argv[1] : "../../platforms/two_hosts.xml");
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());
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"), workerScopedLock, mutex, std::ref(result[i]));
58 sg4::Actor::create("worker", sg4::Host::by_name("Tremblay"), worker, mutex, std::ref(result[i]));
63 for (int i = 0; i < cfg_actor_count; i++)
64 XBT_INFO("Result[%d] -> %d", i, result[i]);