Instantly share code, notes, and snippets.

Embed
What would you like to do?
Test-And-Test-And-Set lock
#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);
}
};
@yohhoy

This comment has been minimized.

Owner

yohhoy commented Jan 19, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment