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