2015-12-08 04:51:55 +08:00
|
|
|
#pragma once
|
2015-07-04 17:50:42 +08:00
|
|
|
|
|
|
|
#include <atomic>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
2016-03-16 03:13:31 +08:00
|
|
|
#include "utils/cpu_relax.hpp"
|
|
|
|
|
2015-07-04 17:50:42 +08:00
|
|
|
class SpinLock
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
|
|
|
|
void lock()
|
|
|
|
{
|
|
|
|
while(lock_flag.test_and_set(std::memory_order_acquire))
|
2016-03-16 03:13:31 +08:00
|
|
|
cpu_relax();
|
|
|
|
///usleep(250);
|
2015-07-04 17:50:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void unlock()
|
|
|
|
{
|
|
|
|
lock_flag.clear(std::memory_order_release);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
// guaranteed by standard to be lock free!
|
|
|
|
std::atomic_flag lock_flag = ATOMIC_FLAG_INIT;
|
|
|
|
};
|