lock free
程序员文章站
2022-04-04 16:28:51
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
上一篇: .NET Core Cache [MemoryCache]
下一篇: Google C++ 编码规范
推荐阅读
-
mysql运行出现Can’t open and lock privilege tables: Inc
-
Android多线程专题:线程间协作Lock、ReadWriteLock
-
oracle table-lock的5种模式
-
基于zookeeper的分布式lock实现
-
php disk_free_space与disk_total_space 函数_PHP教程
-
解决Another app is currently holding the yum lock; waiting for it to exit...问题
-
Oracle table-lock的5种模式
-
oppoencofree2耳机价格?OPPO Enco Free2耳机对比一代的变化
-
mysqli 是否在每次的查询后都需要调用free_result?
-
Linux中显示空闲内存空间的free命令的基本用法