我的 spin lock 代码:
#include <atomic>
#include <unistd.h>
struct SpinLock;
struct SpinLock_t {
private:
std::atomic<char> stat;
static const char UNLOCK_STAT = 0;
static const char LOCK_STAT = 1;
public:
SpinLock_t() : stat(UNLOCK_STAT) {}
private:
friend class SpinLock;
SpinLock_t(const SpinLock_t& s);
SpinLock_t operator=(const SpinLock_t& s);
};
struct SpinLock {
private:
SpinLock_t *s_;
public:
SpinLock(SpinLock_t* s):s_(s) {
char unlock_stat = SpinLock_t::UNLOCK_STAT;
while (!(s_->stat).compare_exchange_weak(unlock_stat,
SpinLock_t::LOCK_STAT, std::memory_order_acq_rel)) {
unlock_stat = SpinLock_t::UNLOCK_STAT;
sleep(0);
}
}
~SpinLock() {
(s_->stat).store(SpinLock_t::UNLOCK_STAT, std::memory_order_release);
}
private:
SpinLock(const SpinLock& s);
SpinLock& operator=(const SpinLock& s);
};