1 #include <iostream>
2 #include <thread>
3 #include <mutex>
4 #include <atomic>
5 using namespace std;
6
7 //全局变量会造成冲突,使得结果不正确
8 //mutex结果正确,速度慢
9 //atomic 结果正确,速度快
10
11
12 //线程安全,多线程访问不冲突
13 //int num = 0;
14
15 //原子变量
16 atomic_int num(
0);
17
18 mutex m;
//互斥
19
20 void run()
21 {
22 for (
int i =
0; i <
100000; i++
)
23 {
24 //m.lock();
25 num++
;
26 //m.unlock();
27 }
28 }
29
30 void main()
31 {
32 clock_t start =
clock();
33 thread th1(run);
34 thread th2(run);
35 th1.join();
36 th2.join();
37 clock_t end =
clock();
38 cout << num <<
endl;
39 cout << end - start <<
"ms" <<
endl;
40
41 cin.
get();
42 }
转载于:https://www.cnblogs.com/xiaochi/p/8546201.html
转载请注明原文地址: https://win8.8miu.com/read-27166.html