TeaSpeakLibrary/src/misc/spin_lock.h

37 lines
836 B
C
Raw Normal View History

2019-06-26 22:11:22 +02:00
#pragma once
#include <atomic>
#include <thread>
2019-07-09 12:29:12 +02:00
#ifdef WIN2
#define always_inline __forceinline
#else
#define always_inline inline __attribute__((__always_inline__))
#endif
2019-06-26 22:11:22 +02:00
class spin_lock {
2019-07-09 12:29:12 +02:00
std::atomic_bool locked{false};
2019-06-26 22:11:22 +02:00
public:
2019-07-09 12:29:12 +02:00
always_inline void lock() {
while (locked.exchange(true, std::memory_order_acquire))
this->wait_until_release();
}
always_inline void wait_until_release() const {
2019-06-26 22:11:22 +02:00
uint8_t round = 0;
2019-07-09 12:29:12 +02:00
while (locked.load(std::memory_order_relaxed)) {
//Yield when we're using this lock for a longer time, which we usually not doing
if(round++ % 8 == 0)
std::this_thread::yield();
}
2019-06-26 22:11:22 +02:00
}
2019-07-09 12:29:12 +02:00
always_inline bool try_lock() {
return !locked.exchange(true, std::memory_order_acquire);
2019-06-26 22:11:22 +02:00
}
2019-07-09 12:29:12 +02:00
always_inline void unlock() {
locked.store(false, std::memory_order_release);
2019-06-26 22:11:22 +02:00
}
};