Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active January 19, 2017 15:41
Show Gist options
  • Save yohhoy/96618ce673b80a3bbbf5 to your computer and use it in GitHub Desktop.
Save yohhoy/96618ce673b80a3bbbf5 to your computer and use it in GitHub Desktop.
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
Copy link
Author

yohhoy commented Jan 19, 2017

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