参见 《深入理解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();
}