-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwait_group.h
More file actions
50 lines (39 loc) · 923 Bytes
/
wait_group.h
File metadata and controls
50 lines (39 loc) · 923 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
39
40
41
42
43
44
45
46
47
48
49
50
/*
Realization of channel concept from GoLang.
ext::WaitGroup wg;
wg.add();
auto thread = std::thread([&]()
{
EXT_DEFER({ wg.done(); });
...
});
// will wait till the end of the thread
wg.done();
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <ext/core/noncopyable.h>
namespace ext {
class WaitGroup : ext::NonCopyable {
private:
std::atomic_int_fast64_t m_counter = 0;
mutable std::mutex m_mutex;
mutable std::condition_variable m_cv;
public:
WaitGroup() = default;
void add(int delta = 1) noexcept {
m_counter += delta;
}
void done() noexcept {
if (m_counter.fetch_sub(1) == 1) {
m_cv.notify_all();
}
}
void wait() const noexcept {
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [&]() { return m_counter == 0; });
}
};
} // namespace ext