C++11实现自旋锁
生活随笔
收集整理的這篇文章主要介紹了
C++11实现自旋锁
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
參見 《深入理解C++11》
#include <thread> #include <atoimic> #include <iostream> #include <unistd.h> using namespace std;std::atomic_flag lock = ATOMIC_FLAG_INIT; void f(int n) {while (lock.test_and_set(std::memory_order_acquire)) { // 嘗試獲得鎖cout << "Waiting" << endl; // 等待}cout << "thread: " << n << endl; }void g(int n) {cout << "thread " << n << " is going to start. " << endl;lock.clear();cout << "thread " << n << " starts working" << endl; }int main() {lock.test_and_set();thread t1(f, 1);thread t2(g, 2);t1.join();usleep(100);t2.join(); }封裝
void Lock(atomic_flag lock) {while(lock.test_and_set()); }void UnLock(atomic_flag lock) {lock.clear(); }總結
以上是生活随笔為你收集整理的C++11实现自旋锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 去澳门机票多少钱啊?
- 下一篇: 中南海多少钱一包啊?