lock free
程序员文章站
2022-06-30 18:34:02
lock free ......
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
推荐阅读
-
详谈innodb的锁(record,gap,Next-Key lock)
-
三星Good Lock 2020今日更新 终于可以自定义专属系统了
-
售票情景解读synchronized和Lock两种锁的区别
-
对python多线程中Lock()与RLock()锁详解
-
[C#学习笔记]lock锁的解释与用法
-
java多线程关键字volatile、lock、synchronized
-
Apache No space left on device: mod_rewrite: could not create rewrite_log_lock Configuration Failed
-
ThinkPad笔记本电脑的Scroll Lock功能如何开启或关闭
-
关键字Lock的简单小例子
-
mysql报错:Deadlock found when trying to get lock; try restarting transaction的解决方法