Skip to content

Instantly share code, notes, and snippets.

@preshing
Created June 13, 2017 02:02
Show Gist options
  • Save preshing/00ccda058761e8d6898e0a4c0a53d2bb to your computer and use it in GitHub Desktop.
Save preshing/00ccda058761e8d6898e0a4c0a53d2bb to your computer and use it in GitHub Desktop.
#include <atomic>
class SpinLock {
std::atomic<int> m_flag = 0;
public:
void lock() {
int expected = 0;
while (!m_flag.compare_exchange_weak(expected, 1, std::memory_order_acquire)) {
expected = 0;
}
}
void unlock() {
m_flag.store(0, std::memory_order_release);
}
};
SpinLock A;
SpinLock B;
void thread1() {
A.lock();
A.unlock();
B.lock();
B.unlock();
}
void thread2() {
B.lock();
A.lock();
A.unlock();
B.unlock();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment