25 lines
533 B
C++
25 lines
533 B
C++
#pragma once
|
|
|
|
#include <atomic>
|
|
#include <thread>
|
|
|
|
class spin_lock {
|
|
std::atomic_flag locked = ATOMIC_FLAG_INIT;
|
|
public:
|
|
void lock() {
|
|
uint8_t round = 0;
|
|
while (locked.test_and_set(std::memory_order_acquire)) {
|
|
//Yield when we're using this lock for a longer time, which we usually not doing
|
|
if(round++ % 8 == 0)
|
|
std::this_thread::yield();
|
|
}
|
|
}
|
|
|
|
inline bool try_lock() {
|
|
return !locked.test_and_set(std::memory_order_acquire);
|
|
}
|
|
|
|
void unlock() {
|
|
locked.clear(std::memory_order_release);
|
|
}
|
|
}; |