Minetest 5.10.0-dev
 
Loading...
Searching...
No Matches
ordered_mutex.h
Go to the documentation of this file.
1// Minetest
2// SPDX-License-Identifier: LGPL-2.1-or-later
3
4#pragma once
5
6#include <cstdint>
7#include <condition_variable>
8
9/*
10 Fair mutex based on ticketing approach.
11 Satisfies `Mutex` C++11 requirements.
12*/
14public:
16
17 void lock()
18 {
19 std::unique_lock autolock(cv_lock);
20 const auto ticket = next_ticket++;
21 cv.wait(autolock, [&] { return counter == ticket; });
22 }
23
24 bool try_lock()
25 {
26 std::lock_guard autolock(cv_lock);
27 if (counter != next_ticket)
28 return false;
30 return true;
31 }
32
33 void unlock()
34 {
35 {
36 std::lock_guard autolock(cv_lock);
37 counter++;
38 }
39 cv.notify_all(); // intentionally outside lock
40 }
41
42private:
43 std::condition_variable cv;
44 std::mutex cv_lock;
45 uint_fast32_t next_ticket, counter;
46};
Definition ordered_mutex.h:13
uint_fast32_t counter
Definition ordered_mutex.h:45
void unlock()
Definition ordered_mutex.h:33
std::mutex cv_lock
Definition ordered_mutex.h:44
bool try_lock()
Definition ordered_mutex.h:24
ordered_mutex()
Definition ordered_mutex.h:15
void lock()
Definition ordered_mutex.h:17
uint_fast32_t next_ticket
Definition ordered_mutex.h:45
std::condition_variable cv
Definition ordered_mutex.h:43