-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathc29_class_with_mutex.cpp
More file actions
55 lines (49 loc) · 939 Bytes
/
Copy pathc29_class_with_mutex.cpp
File metadata and controls
55 lines (49 loc) · 939 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
53
54
55
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
class Vector
{
public:
Vector() = default;
~Vector() = default;
void push_back(int d)
{
_m.lock();
_data.push_back(d);
_m.unlock();
}
void print()
{
// comment out the mutex lock to see what happens
_m.lock();
for (const auto d : _data)
{
std::cout << d << " ";
}
std::cout << std::endl;
_m.unlock();
}
private:
std::vector<int> _data;
std::mutex _m;
};
void pushToVector(Vector& v)
{
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
v.print();
}
}
int main()
{
Vector v;
std::thread t1{pushToVector, std::ref(v)};
std::thread t2{pushToVector, std::ref(v)};
t1.join();
t2.join();
return 0;
}