-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConditionVariable.h
More file actions
60 lines (53 loc) · 1.15 KB
/
Copy pathConditionVariable.h
File metadata and controls
60 lines (53 loc) · 1.15 KB
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
// SPDX-FileCopyrightText: 2015-2020, 2022-2023 Carlo Wood
// SPDX-License-Identifier: MIT
#pragma once
#include "AIMutex.h"
#include <condition_variable>
namespace threadsafe
{
// Like std::condition_variable but derived from AIMutex and using that as mutex.
//
// Usage:
//
// Declaration:
//
// using foo_type = threadsafe::Unlocked<Foo, threadsafe::policy::Primitive<threadsafe::ConditionVariable>>;
// foo_type foo_cv;
//
// Waiting:
//
// foo_type::wat foo_w(foo_cv);
// foo_w.wait([&](){ return foo_w->done(); });
//
// Notifying:
//
// foo_type::wat foo_w(foo_cv);
// foo_w->set_done();
// foo_w.notify_one();
//
class ConditionVariable : public AIMutex
{
private:
std::condition_variable_any m_condition_variable;
public:
template<typename Predicate>
void wait(Predicate pred)
{
// Usage:
//
// threadsafe::ConditionVariable cv;
//
// cv.lock();
// cv.wait([](){ return done; });
// cv.unlock();
//
// For prefered usage, see above.
ASSERT(is_self_locked());
m_condition_variable.wait(*this, pred);
}
void notify_one()
{
m_condition_variable.notify_one();
}
};
} // namespace threadsafe