Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
ticket-based fair mutex implementation
#include <condition_variable>
#include <mutex>
#include <thread>
class fair_mutex {
std::mutex mtx_;
std::condition_variable cv_;
unsigned int next_, curr_;
fair_mutex() : next_(0), curr_(0) {}
~fair_mutex() = default;
fair_mutex(const fair_mutex&) = delete;
fair_mutex& operator=(const fair_mutex&) = delete;
void lock()
std::unique_lock<decltype(mtx_)> lk(mtx_);
const unsigned int self = next_++;
cv_.wait(lk, [&]{ return (self == curr_); });
bool try_lock()
std::lock_guard<decltype(mtx_)> lk(mtx_);
if (next_ != curr_)
return false;
return true;
void unlock()
std::lock_guard<decltype(mtx_)> lk(mtx_);

This comment has been minimized.

Copy link
Owner Author

commented Jan 19, 2017


This comment has been minimized.

Copy link

commented Aug 14, 2018

Can you please provide explanation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.