此实例通过c++11实现。
#pragma once
#include
#include
class Spinlock {
public:
Spinlock() : flag(ATOMIC_FLAG_INIT), wait_count(2000) {}
void lock() {
int64_t i = 0;
while(flag.test_and_set(std::memory_order_acquire)) {
__asm__ ("pause");
if (++i > wait_count) {
sched_yield();
i = 0;
}
}
}
bool try_lock() {
if (flag.test_and_set(std::memory_order_acquire)) {
return false;
}
return true;
}
void unlock() {
flag.clear(std::memory_order_release);
}
private :
std::atomic_flag flag;
int32_t wait_count;
};