1 /* Copyright (c) 2006-2017. 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 <mutex> /* std::mutex and std::lock_guard */
7 #include "simgrid/s4u.hpp" /* All of S4U */
11 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
13 /* This worker uses a classical mutex */
14 static void worker(simgrid::s4u::MutexPtr mutex, int& result)
16 // lock the mutex before enter in the critical section
19 XBT_INFO("Hello s4u, I'm ready to compute after a regular lock");
20 // And finaly add it to the results
22 XBT_INFO("I'm done, good bye");
24 // You have to unlock the mutex if you locked it manually.
25 // Beware of exceptions preventing your unlock() from being executed!
29 static void workerLockGuard(simgrid::s4u::MutexPtr mutex, int& result)
31 // Simply use the std::lock_guard like this
32 // It's like a lock() that would do the unlock() automatically when getting out of scope
33 std::lock_guard<simgrid::s4u::Mutex> lock(*mutex);
35 // then you are in a safe zone
36 XBT_INFO("Hello s4u, I'm ready to compute after a lock_guard");
39 XBT_INFO("I'm done, good bye");
41 // Nothing specific here: the unlock will be automatic
47 simgrid::s4u::MutexPtr mutex = simgrid::s4u::Mutex::createMutex();
49 for (int i = 0; i < NB_ACTOR * 2 ; i++) {
50 // To create a worker use the static method simgrid::s4u::Actor.
52 simgrid::s4u::Actor::createActor("worker", simgrid::s4u::Host::by_name("Jupiter"), workerLockGuard, mutex, std::ref(result));
54 simgrid::s4u::Actor::createActor("worker", simgrid::s4u::Host::by_name("Tremblay"), worker, mutex, std::ref(result));
57 simgrid::s4u::this_actor::sleep_for(10);
58 XBT_INFO("Results is -> %d", result);
61 int main(int argc, char **argv)
63 simgrid::s4u::Engine e(&argc, argv);
64 e.loadPlatform("../../platforms/two_hosts.xml");
65 simgrid::s4u::Actor::createActor("main", simgrid::s4u::Host::by_name("Tremblay"), master);