Skip to content

Instantly share code, notes, and snippets.

Last active July 4, 2021 13:19
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
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_);
Copy link

yohhoy commented Jan 19, 2017

Copy link

Can you please provide explanation?

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