-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC11Mutex.cpp
More file actions
60 lines (46 loc) · 1.11 KB
/
C11Mutex.cpp
File metadata and controls
60 lines (46 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <thread>
#include <iostream>
#include <vector>
#include <mutex>
#include <string>
// Compiler: Microsoft Visual C++ Compiler Nov 2012 CTP (v120_CTP_Nov2012)
struct SharedThing {
public:
SharedThing(int startValue){
counter = startValue;
}
void increase(const std::string& message){
// When std::lock_guard<std::mutex> instance is created lock() is called on the mutex.
// When destructed the lock is released.
std::lock_guard<std::mutex> guard(lock);
++counter;
std::cout << message << " Counter:" << counter << std::endl;
}
int currentCount(){
return counter;
}
private:
std::mutex lock;
int counter;
};
void step1(SharedThing* thing){
thing->increase("Step 1");
}
int main(){
auto counter = new SharedThing(0);
std::vector<std::thread> threads;
for(int i = 0; i < 400; ++i){
// Step 1
threads.push_back(std::thread(step1, counter));
// Step 2
threads.push_back(std::thread([&counter](){
counter->increase("Step 2");
}
));
}
for(auto& thread : threads){
thread.join();
}
std::cout << "Final count: " << counter->currentCount();
return 0;
}