licks 发表于 2023-11-30 16:42

利用C++11及其以上标准,封装自旋锁

本帖最后由 wushaominkk 于 2023-12-1 09:17 编辑

/************************************************************************
SpinLockTAS<> sp_lock;
std::unique_lock<SpinLockTAS<>> lk(sp_lock);
功能: TAS自旋锁
返回值:void
************************************************************************/
template<::std::size_t sleepWhenLockFailedInMicroSecond = ::std::size_t(-1)>
class SpinLockTAS
{
public:
    void lock();
    void unlock();
private:
    ::std::atomic_flag locked_flag = ATOMIC_FLAG_INIT;
};

/************************************************************************
SpinLockCAS<> sp_lock;
std::unique_lock<SpinLockCAS<>> lk(sp_lock);
功能: CAS自旋锁
************************************************************************/
template<::std::size_t sleepWhenLockFailedInMicroSecond = ::std::size_t(-1)>
class SpinLockCAS
{
public:
    void lock();
    void unlock();

private:
    ::std::atomic<bool> locked_flag;
};

template<::std::size_t sleepWhenLockFailedInMicroSecond>
void SpinLockTAS<sleepWhenLockFailedInMicroSecond>::lock()
{
   while (this->locked_flag.test_and_set())
   {
       if (sleepWhenLockFailedInMicroSecond <= ::std::size_t(0))
         ::std::this_thread::yield();
       else if (sleepWhenLockFailedInMicroSecond > 0)
         ::std::this_thread::sleep_for(::std::chrono::microseconds(sleepWhenLockFailedInMicroSecond));
   }
}

template<::std::size_t sleepWhenLockFailedInMicroSecond>
void SpinLockTAS<sleepWhenLockFailedInMicroSecond>::unlock()
{
   this->locked_flag.clear();
}

template<::std::size_t sleepWhenLockFailedInMicroSecond>
void SpinLockCAS<sleepWhenLockFailedInMicroSecond>::lock()
{
    bool expect = false;

    while (!this->locked_flag.compare_exchange_weak(expect, true))
    {
       expect = false;
       if (sleepWhenLockFailedInMicroSecond <= ::std::size_t(0))
         ::std::this_thread::yield();
       else if (sleepWhenLockFailedInMicroSecond > 0)
         ::std::this_thread::sleep_for(::std::chrono::microseconds(sleepWhenLockFailedInMicroSecond));
    }
}

template<::std::size_t sleepWhenLockFailedInMicroSecond>
void SpinLockCAS<sleepWhenLockFailedInMicroSecond>::unlock()
{
    this->locked_flag.store(false);
}

苏紫方璇 发表于 2023-11-30 22:09

推荐使用这个帖子的代码插入方法
【公告】发帖代码插入以及添加链接教程(有福利)
https://www.52pojie.cn/thread-713042-1-1.html
(出处: 吾爱破解论坛)

FruitBaby 发表于 2023-12-2 18:39

搞c++的都是大佬,,

licks 发表于 2023-12-5 23:18

苏紫方璇 发表于 2023-11-30 22:09
推荐使用这个帖子的代码插入方法
【公告】发帖代码插入以及添加链接教程(有福利)
https://www.52pojie. ...

我得研究研究,平时工作太忙

xuebing1995 发表于 2023-12-14 09:34

支持新人
页: [1]
查看完整版本: 利用C++11及其以上标准,封装自旋锁