Last active
January 19, 2017 15:41
-
-
Save yohhoy/96618ce673b80a3bbbf5 to your computer and use it in GitHub Desktop.
Test-And-Test-And-Set lock
This file contains 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 <thread> | |
#include <atomic> | |
class ttas_mutex { | |
std::atomic<bool> locked_; | |
public: | |
ttas_mutex() | |
: locked_(false) {} | |
ttas_mutex(const ttas_mutex&) = delete; | |
ttas_mutex& operator=(const ttas_mutex&) = delete; | |
void lock() { | |
for (;;) { | |
bool state = false; | |
if (locked_.compare_exchange_weak(state, true, memory_order_acquire)) | |
break; | |
while (locked_.load(memory_order_relaxed) == state) | |
std::this_thread::yield(); | |
} | |
} | |
void unlock() { | |
locked_.store(false, memory_order_release); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
integrate into https://github.com/yohhoy/yamc