forked from laurynas-biveinis/unodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_sync.hpp
61 lines (47 loc) · 1.47 KB
/
thread_sync.hpp
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
// Copyright 2020-2025 UnoDB contributors
#ifndef UNODB_DETAIL_THREAD_SYNC_HPP
#define UNODB_DETAIL_THREAD_SYNC_HPP
// Should be the first include
#include "global.hpp" // IWYU pragma: keep
#include <array>
#include <condition_variable>
#include <mutex>
#include "assert.hpp"
namespace unodb::detail {
class [[nodiscard]] thread_sync final {
public:
thread_sync() noexcept = default;
UNODB_DETAIL_DISABLE_MSVC_WARNING(26447)
~thread_sync() noexcept { UNODB_DETAIL_ASSERT(is_reset()); }
UNODB_DETAIL_RESTORE_MSVC_WARNINGS()
[[nodiscard]] bool is_reset() const {
const std::lock_guard lock{sync_mutex};
return !flag;
}
void notify() {
{
const std::lock_guard lock{sync_mutex};
flag = true;
}
sync.notify_one();
}
void wait() {
std::unique_lock lock{sync_mutex};
sync.wait(lock, [&inner_flag = flag] { return inner_flag; });
flag = false;
lock.unlock();
}
thread_sync(const thread_sync &) = delete;
thread_sync(thread_sync &&) = delete;
thread_sync &operator=(const thread_sync &) = delete;
thread_sync &operator=(thread_sync &&) = delete;
private:
// Replace with a C++20 latch when that's available
std::condition_variable sync;
mutable std::mutex sync_mutex;
bool flag{false};
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,fuchsia-statically-constructed-objects)
inline std::array<thread_sync, 6> thread_syncs;
} // namespace unodb::detail
#endif // UNODB_DETAIL_THREAD_SYNC_HPP