-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTicketMutex.h
More file actions
38 lines (30 loc) · 854 Bytes
/
Copy pathTicketMutex.h
File metadata and controls
38 lines (30 loc) · 854 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// Created by michal on 21.07.2022.
//
#ifndef COMMANDPATTERN_TICKETMUTEX_H
#define COMMANDPATTERN_TICKETMUTEX_H
#include <atomic>
#include <mutex>
struct TicketMutex
{
void lock()
{
const auto my = in.fetch_add(1, std::memory_order_acquire);
while (true) {
const auto now = out.load(std::memory_order_acquire);
if (my == now) {
return;
}
out.wait(now, std::memory_order_relaxed);
}
}
void unlock()
{
out.fetch_add(1, std::memory_order_release);
out.notify_all();
}
private:
alignas(std::hardware_destructive_interference_size) std::atomic<int> in = ATOMIC_VAR_INIT(0);
alignas(std::hardware_destructive_interference_size) std::atomic<int> out = ATOMIC_VAR_INIT(0);
};
#endif //COMMANDPATTERN_TICKETMUTEX_H