Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active July 4, 2021 13:19
Show Gist options
  • Save yohhoy/6018695 to your computer and use it in GitHub Desktop.
Save yohhoy/6018695 to your computer and use it in GitHub Desktop.
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
Copy link
Author

yohhoy commented Jan 19, 2017

@shriganeshs-zz
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