C++通过原子变量代替互斥量
废话不多说,直接上代码。
实现类似lock_guard功能
#include <atomic>
#include <thread>
class ClockGuard
{
public:
ClockGuard(std::atomic_flag & atomic):m_lockedFlag(atomic)
{
lock();
}
~ClockGuard()
{
unlock();
}
void lock() const
{
while(m_lockedFlag.test_and_set(std::memory_order_acquire))
{
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
}
void unlock() const
{
m_lockedFlag.clear(std::memory_order_release);
}
private:
std::atomic_flag &m_lockedFlag;
};
ClockGuard
的用法和lock_guard一样。
测试
class student
{
public:
student();
void move() const
{
ClockGuard locker(this->m_lockedFlag);
std::cout << "自旋锁" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
private:
mutable std::atomic_flag m_lockedFlag = ATOMIC_FLAG_INIT;
};
int main()
{
student st;
unsigned int count = 8;
for (unsigned int i = 0; i < count; ++i)
{
std::thread t(&student::move, &st);
t.detach();
}
std::this_thread::sleep_for(std::chrono::milliseconds(20000));
}
结果
程序执行后立刻输出 “自旋锁”,然后每隔2s输出一个。
自旋锁
自旋锁
自旋锁
自旋锁
自旋锁
自旋锁
自旋锁
自旋锁