Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[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   simgrid::s4u::Actor workers[NB_ACTOR*2];
50
51   for (int i = 0; i < NB_ACTOR * 2 ; i++) {
52     // To create a worker use the static method simgrid::s4u::Actor.
53     if((i % 2) == 0 )
54       workers[i] = simgrid::s4u::Actor("worker",
55         simgrid::s4u::Host::by_name("Jupiter"),
56         workerLockGuard, mutex, std::ref(result));
57     else
58       workers[i] = simgrid::s4u::Actor("worker",
59         simgrid::s4u::Host::by_name("Tremblay"),
60         worker, mutex, std::ref(result));
61   }
62
63   simgrid::s4u::this_actor::sleep(10);
64   XBT_INFO("Results is -> %d", result);
65 }
66
67 int main(int argc, char **argv)
68 {
69   simgrid::s4u::Engine *e = new simgrid::s4u::Engine(&argc,argv);
70   e->loadPlatform("../../platforms/two_hosts.xml");
71   simgrid::s4u::Actor("main", simgrid::s4u::Host::by_name("Tremblay"), master);
72   e->run();
73   return 0;
74 }