-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
latch.h
86 lines (71 loc) · 1.98 KB
/
latch.h
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#pragma once
#ifdef __cpp_lib_latch
#include <latch>
#endif
namespace til
{
#ifdef __cpp_lib_latch
using latch = std::latch;
#else
class latch
{
public:
[[nodiscard]] static constexpr ptrdiff_t max() noexcept
{
return std::numeric_limits<ptrdiff_t>::max();
}
constexpr explicit latch(const ptrdiff_t expected) noexcept :
counter{ expected }
{
assert(expected >= 0);
}
latch(const latch&) = delete;
latch& operator=(const latch&) = delete;
void count_down(const ptrdiff_t n = 1) noexcept
{
assert(n >= 0);
const auto old = counter.fetch_sub(n, std::memory_order_release);
if (old == n)
{
WakeByAddressAll(&counter);
return;
}
assert(old > n);
}
[[nodiscard]] bool try_wait() const noexcept
{
return counter.load(std::memory_order_acquire) == 0;
}
void wait() const noexcept
{
while (true)
{
auto current = counter.load(std::memory_order_acquire);
if (current == 0)
{
return;
}
assert(current > 0);
WaitOnAddress(const_cast<decltype(counter)*>(&counter), ¤t, sizeof(counter), INFINITE);
}
}
void arrive_and_wait(const ptrdiff_t n = 1) noexcept
{
assert(n >= 0);
auto old = counter.fetch_sub(n, std::memory_order_acq_rel);
if (old == n)
{
WakeByAddressAll(&counter);
return;
}
assert(old > n);
WaitOnAddress(&counter, &old, sizeof(counter), INFINITE);
wait();
}
private:
std::atomic<ptrdiff_t> counter;
};
#endif
}