Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[s4u] Allocate Actors on the heap and return ActorPtr
[simgrid.git] / examples / s4u / mutex / s4u_mutex.cpp
1 /* Copyright (c) 2006-2015. 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 <functional>
7 #include <mutex>
8
9 #include <xbt/sysdep.h>
10
11 #include "simgrid/s4u.h"
12
13 #define NB_ACTOR 2
14
15 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_test, "a sample log category");
16
17 static void worker(simgrid::s4u::Mutex mutex, int& result)
18 {
19   // Do the calculation
20   simgrid::s4u::this_actor::execute(1000);
21
22   // lock the mutex before enter in the critical section
23   std::lock_guard<simgrid::s4u::Mutex> lock(mutex);
24   XBT_INFO("Hello s4u, I'm ready to compute");
25
26   // And finaly add it to the results
27   result += 1;
28   XBT_INFO("I'm done, good bye");
29 }
30
31 static void workerLockGuard(simgrid::s4u::Mutex mutex, int& result)
32 {
33   simgrid::s4u::this_actor::execute(1000);
34
35   // Simply use the std::lock_guard like this
36   std::lock_guard<simgrid::s4u::Mutex> lock(mutex);
37
38   // then you are in a safe zone
39   XBT_INFO("Hello s4u, I'm ready to compute");
40   // update the results
41   result += 1;
42   XBT_INFO("I'm done, good bye");
43 }
44
45 static void master()
46 {
47   int result = 0;
48   simgrid::s4u::Mutex mutex;
49
50   for (int i = 0; i < NB_ACTOR * 2 ; i++) {
51     // To create a worker use the static method simgrid::s4u::Actor.
52     if((i % 2) == 0 )
53       simgrid::s4u::Actor::createActor("worker", simgrid::s4u::Host::by_name("Jupiter"),  workerLockGuard, mutex, std::ref(result));
54     else
55       simgrid::s4u::Actor::createActor("worker", simgrid::s4u::Host::by_name("Tremblay"), worker,          mutex, std::ref(result));
56   }
57
58   simgrid::s4u::this_actor::sleep(10);
59   XBT_INFO("Results is -> %d", result);
60 }
61
62 int main(int argc, char **argv)
63 {
64   simgrid::s4u::Engine *e = new simgrid::s4u::Engine(&argc,argv);
65   e->loadPlatform("../../platforms/two_hosts.xml");
66   simgrid::s4u::Actor::createActor("main", simgrid::s4u::Host::by_name("Tremblay"), master);
67   e->run();
68   return 0;
69 }