Created
June 13, 2017 02:02
-
-
Save preshing/00ccda058761e8d6898e0a4c0a53d2bb to your computer and use it in GitHub Desktop.
Rewrite of example from http://preshing.com/20170612/can-reordering-of-release-acquire-operations-introduce-deadlock/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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