-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
42 lines (33 loc) · 828 Bytes
/
mutex.cpp
File metadata and controls
42 lines (33 loc) · 828 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
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex gLock;
static int shared_value = 0;
void increment()
{
gLock.lock();
// critical region starts, only one thread can access this block
shared_value++;
gLock.unlock(); // critical region ends
}
int main()
{
auto lambda = [](int x)
{
std::cout << "This thread is " << std::this_thread::get_id() << std::endl;
std::cout << " Argument is: " << x << std::endl;
};
std::vector<std::thread> threads;
for (int i = 0; i < 1000; i++)
{
threads.push_back(std::thread(increment));
}
for (int i = 0; i < 1000; i++)
{
threads[i].join();
}
std::cout << "shared value is: " << shared_value << std::endl;
// shared value exactly will be 1000
return 0;
}