Instantly share code, notes, and snippets.

Embed
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_;
public:
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;
++next_;
return true;
}
void unlock()
{
std::lock_guard<decltype(mtx_)> lk(mtx_);
++curr_;
cv_.notify_all();
}
};
@yohhoy

This comment has been minimized.

Owner

yohhoy commented Jan 19, 2017

@shriganeshs

This comment has been minimized.

shriganeshs 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