-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread2.cpp
More file actions
52 lines (45 loc) · 736 Bytes
/
thread2.cpp
File metadata and controls
52 lines (45 loc) · 736 Bytes
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
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
using namespace std;
class Counter
{
public:
Counter(int _value):value(_value){}
void increaseValue()
{
std::lock_guard<std::mutex> lock(mutex);
++value;
}
void decreaseValue()
{
std::lock_guard<std::mutex> lock(mutex);
if(value == 0)
throw "Value cannot be less than 0";
--value;
}
int value;
std::mutex mutex;
};
int main()
{
Counter counter(0);
std::vector<thread> threadVec;
for (int i = 0; i < 5; ++i)
{
threadVec.push_back(thread([&counter]()
{
for(int j = 0; j < 1000; ++j)
{
counter.increaseValue();
}
}
));
}
for (auto& thread : threadVec)
{
thread.join();
}
cout<<counter.value<<endl;
}