Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
remove a teshsuite example that is superseeded by a proper example
[simgrid.git] / examples / s4u / mutex / s4u_mutex.cpp
1 /* Copyright (c) 2006-2017. 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 <mutex> /* std::mutex and std::lock_guard */
7 #include "simgrid/s4u.hpp" /* All of S4U */
8
9 #define NB_ACTOR 6
10
11 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
12
13 /* This worker uses a classical mutex */
14 static void worker(simgrid::s4u::MutexPtr mutex, int& result)
15 {
16   // lock the mutex before enter in the critical section
17   mutex->lock();
18
19   XBT_INFO("Hello s4u, I'm ready to compute after a regular lock");
20   // And finaly add it to the results
21   result += 1;
22   XBT_INFO("I'm done, good bye");
23
24   // You have to unlock the mutex if you locked it manually.
25   // Beware of exceptions preventing your unlock() from being executed!
26   mutex->unlock();
27 }
28
29 static void workerLockGuard(simgrid::s4u::MutexPtr mutex, int& result)
30 {
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);
34
35   // then you are in a safe zone
36   XBT_INFO("Hello s4u, I'm ready to compute after a lock_guard");
37   // update the results
38   result += 1;
39   XBT_INFO("I'm done, good bye");
40
41   // Nothing specific here: the unlock will be automatic
42 }
43
44 static void master()
45 {
46   int result = 0;
47   simgrid::s4u::MutexPtr mutex = simgrid::s4u::Mutex::createMutex();
48
49   for (int i = 0; i < NB_ACTOR * 2 ; i++) {
50     // To create a worker use the static method simgrid::s4u::Actor.
51     if((i % 2) == 0 )
52       simgrid::s4u::Actor::createActor("worker", simgrid::s4u::Host::by_name("Jupiter"),  workerLockGuard, mutex, std::ref(result));
53     else
54       simgrid::s4u::Actor::createActor("worker", simgrid::s4u::Host::by_name("Tremblay"), worker,          mutex, std::ref(result));
55   }
56
57   simgrid::s4u::this_actor::sleep_for(10);
58   XBT_INFO("Results is -> %d", result);
59 }
60
61 int main(int argc, char **argv)
62 {
63   simgrid::s4u::Engine *e = new simgrid::s4u::Engine(&argc,argv);
64   e->loadPlatform("../../platforms/two_hosts.xml");
65   simgrid::s4u::Actor::createActor("main", simgrid::s4u::Host::by_name("Tremblay"), master);
66   e->run();
67
68   delete e;
69   return 0;
70 }