examples/mutex.cpp
Go to the documentation of this file.
1 
8 /*****************************************************************************
9 ** Platform Check
10 *****************************************************************************/
11 
12 #include <ecl/config.hpp>
13 
14 /*****************************************************************************
15 ** Includes
16 *****************************************************************************/
17 
18 #include <iostream>
19 #include <vector>
20 #include "../../include/ecl/threads/mutex.hpp"
21 #include "../../include/ecl/threads/thread.hpp"
22 #include <ecl/time/sleep.hpp>
23 
24 int shared_value = 0;
25 ecl::Mutex mutex;
26 
27 void f() {
28  ecl::Sleep sleep;
29  sleep(1);
30 
31  std::cout << "Thread: enter blocking" << std::endl;
32  mutex.lock();
33 
34  shared_value = 10;
35  std::cout << "Thread: sets shared_value to 10" << std::endl;
36 
37  mutex.unlock();
38  std::cout << "Thread: leave blocking" << std::endl;
39 }
40 
41 int main() {
42 
43  std::cout << std::endl;
44  std::cout << "***********************************************************" << std::endl;
45  std::cout << " Mutex" << std::endl;
46  std::cout << "***********************************************************" << std::endl;
47  std::cout << std::endl;
48 
49  std::cout << "Lock" << std::endl;
50  mutex.lock();
51 
52  std::cout << "Unlock" << std::endl;
53  mutex.unlock();
54 
55  std::cout << "Trylock" << std::endl;
56  mutex.trylock();
57 
58  std::cout << "Try to lock block already locked" << std::endl;
59  if (mutex.trylock()) {
60  std::cout << "Abnormal" << std::endl;
61  } else {
62  std::cout << "Failed(Normal)" << std::endl;
63  }
64 
65  std::cout << "Unlock" << std::endl;
66  mutex.unlock();
67 
68  std::cout << std::endl;
69  std::cout << "***********************************************************" << std::endl;
70  std::cout << " Synchronization" << std::endl;
71  std::cout << "***********************************************************" << std::endl;
72  std::cout << std::endl;
73 
74  ecl::Thread thread_f(f);
75  ecl::Sleep sleep;
76 
77  std::cout << "Main: enter blocking" << std::endl;
78  mutex.lock();
79  sleep(3);
80 
81  if (shared_value < 5) {
82  std::cout << "shared_value(" << shared_value << ") is smaller than 5" << std::endl;
83  } else {
84  std::cout << "shared_value(" << shared_value << ") is larger than 5" << std::endl;
85  }
86 
87  mutex.unlock();
88  std::cout << "Main: leave blocking" << std::endl;
89 
90  thread_f.join();
91 
92  std::cout << std::endl;
93  std::cout << "***********************************************************" << std::endl;
94  std::cout << " Passed" << std::endl;
95  std::cout << "***********************************************************" << std::endl;
96  std::cout << std::endl;
97 
98  return 0;
99 }
int main()
void f()
int shared_value
ecl::Mutex mutex


ecl_threads
Author(s): Daniel Stonier
autogenerated on Mon Feb 28 2022 22:18:53