#include <atomic>
#include <iostream>
#include <thread>
class spinlock_mutex
{
std::atomic_flag flag;
public:
// 1.以false状态初始化flag
spinlock_mutex():flag(ATOMIC_FLAG_INIT){}
void lock()
{
// 2.thread1: 设置flag为true, 同时返回修改前的状态(false), 非阻塞
// 5.thread2: 设置flag为true, 同时返回修改前的状态(true), 阻塞
// 7.thread2: 设置flag为true, 同时返回修改前的状态(false), 非阻塞
while(flag.test_and_set(std::memory_order_acquire));
}
void unlock()
{
// 6.thread1: 解锁释放互斥量,修改flag为false
flag.clear(std::memory_order_release);
}
};
spinlock_mutex test_mutex;
void thread1Func() {
test_mutex.lock();
std::cout << __FUNCTION__ << std::endl;
// 3.延迟3秒
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
// 6.解锁释放互斥量
test_mutex.unlock();
}
void thread2Func() {
// 4.加锁
test_mutex.lock();
std::cout << __FUNCTION__ << std::endl;
// 8.解锁
test_mutex.unlock();
}
int main() {
std::thread th1(thread1Func);
std::thread th2(thread2Func);
// 9.等待线程结束
th1.join();
th2.join();
// 10.程序结束
return 0;
}