-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
36 lines (36 loc) · 751 Bytes
/
mutex.cpp
File metadata and controls
36 lines (36 loc) · 751 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
#include <iostream>
#include <list>
#include <thread>
#include <string>
#include <mutex>
std::list<int> g_Data;
const int SIZE = 10000;
std::mutex g_Mutex;
void Download()
{
for (int i = 0; i < SIZE; ++i)
{
// Use std::lock_guard to lock a mutex (RAII)
std::lock_guard<std::mutex> mtx(g_Mutex);
g_Data.push_back(i);
if (i == 500)
return;
}
}
void Download2()
{
for (int i = 0; i < SIZE; ++i)
{
std::lock_guard<std::mutex> mtx(g_Mutex);
g_Data.push_back(i);
}
}
int main()
{
std::thread thDownloader(Download);
std::thread thDownloader2(Download2);
thDownloader.join();
thDownloader2.join();
std::cout << g_Data.size() << std::endl;
return 0;
}