C++11多线程基础:使用std::atomic_flag实现自旋锁

#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值