Last active
April 15, 2025 23:31
-
-
Save yohhoy/6018695 to your computer and use it in GitHub Desktop.
ticket-based fair mutex implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} | |
}; |
Can you please provide explanation?
This will not work as fair mutex. Reason: self = next_++
assignment is done under regular (non-fair) mutex. This defeats the purpose of the whole implementation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
integrate into https://github.com/yohhoy/yamc