yhkylin-backup-tools/common/spinlock_mutex.h

38 lines
754 B
C
Raw Normal View History

2021-08-06 10:20:03 +08:00
/**
* @author
* @note c++11, std::shared_lock<spinlock_mutex>std::lock_guard<spinlock_mutex>
*/
#pragma once
#ifndef __SPINLOCK_MUTEX_H__
#define __SPINLOCK_MUTEX_H__
#include <atomic>
2021-10-26 09:24:05 +08:00
#include <mutex>
2021-08-06 10:20:03 +08:00
class spinlock_mutex
{
std::atomic_flag flag = ATOMIC_FLAG_INIT; //注意:不能用初始化列表初始化,拷贝构造和复制构造函数已经删除
public:
spinlock_mutex() {}
void lock()
{
while (flag.test_and_set(std::memory_order_acquire));
}
void unlock()
{
flag.clear(std::memory_order_release);
}
bool try_lock()
{
return !flag.test_and_set(std::memory_order_acquire);
}
};
#endif //!__SPINLOCK_MUTEX_H__