lock free

2018-06-17 20:32:25来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 1 #include <thread>
 2 #include <iostream>
 3 #include <mutex>
 4 #include <atomic>
 5 #include <chrono>
 6 
 7 using namespace std;
 8 
 9 #ifdef _LOCK_FREE
10 
11 atomic<int> i = 0;
12 
13 void foo() {
14     int count = 10000000;
15     while (count--)
16     {
17         i++;
18     }
19 }
20 
21 int main()
22 {
23     chrono::steady_clock::time_point start_time = chrono::steady_clock::now();
24 
25     thread thread1(foo);
26     thread thread2(foo);
27 
28     thread1.join();
29     thread2.join();
30 
31     cout << "i = " << i << endl;
32 
33     chrono::steady_clock::time_point end_time = chrono::steady_clock::now();
34     chrono::duration<double> time_span = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
35     cout << "lock free elpased time: " << time_span.count() << " ms" << endl;
36 
37     system("pause");
38 
39     return 0;
40 }
41 #endif // _LOCK_FREE
42 
43 
44 
45 #ifdef _MUTEX_LOCK
46 int i = 0;
47 mutex g_mutex;
48 
49 
50 void foo() {
51     int count = 10000000;
52     while (count--)
53     {
54         g_mutex.lock();
55         i++;
56         g_mutex.unlock();
57     }
58 }
59 
60 int main()
61 {
62     chrono::steady_clock::time_point start_time = chrono::steady_clock::now();
63 
64     thread thread1(foo);
65     thread thread2(foo);
66 
67     thread1.join();
68     thread2.join();
69 
70     cout << "i = " << i << endl;
71 
72     chrono::steady_clock::time_point end_time = chrono::steady_clock::now();
73     chrono::duration<double> time_span = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
74     cout << "mutex lock elpased time: " << time_span.count() << " ms" << endl;
75 
76     system("pause");
77 
78     return 0;
79 }
80 #endif _MUTEX_LOCK

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:自动曝光修复算法 附完整C代码

下一篇:STL笔记