-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomicTest.cpp
More file actions
55 lines (49 loc) · 1.06 KB
/
Copy pathatomicTest.cpp
File metadata and controls
55 lines (49 loc) · 1.06 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
//
// Created by william on 2021/7/17.
//
#include <thread>
#include <iostream>
#include <vector>
std::atomic<long> g_count = 0;
long g_count1 = 0;
std::mutex g_mutex;
void threadFnc()
{
for (int i = 0; i < 100000; ++i)
{
g_count++;
}
}
void threadFnc1()
{
for (int i = 0; i < 100000; ++i)
{
g_count1++;
}
}
void threadFnc2()
{
std::lock_guard<std::mutex> lock(g_mutex);
for (int i = 0; i < 100000; ++i)
{
g_count1++;
}
}
void atomicTest()
{
std::vector<std::thread> threads;
auto starTime = std::chrono::system_clock::now();
threads.reserve(10);
for (int i = 0; i < 10; ++i)
{
threads.emplace_back(threadFnc);
}
for (int i = 0; i < 10; ++i)
{
threads[i].join();
}
auto endTime = std::chrono::system_clock::now();
std::cout << "g_count:" << g_count << std::endl;
std::cout << "g_count1:" << g_count1 << std::endl;
std::cout << "during Time: " << std::chrono::duration_cast<std::chrono::milliseconds>(endTime - starTime).count() << std::endl;
}