Debian Codegraph @

LspCpp/include/LibLsp/JsonRpc/Condition.h

raw
1 #pragma once
2 #include <condition_variable>
3 template<class T>
4 class Condition
5 {
6 public:
7 std::mutex m_mutex;
8 std::condition_variable m_condition;
9 ~Condition()
10 {
11 m_condition.notify_all();
12 }
13 void notify(std::unique_ptr<T> data) noexcept
14 {
15 {
16 std::lock_guard<std::mutex> eventLock(m_mutex);
17 any.swap(data);
18 }
19 // wake up one waiter
20 m_condition.notify_one();
21 };
22
23 std::unique_ptr<T> wait(unsigned timeout = 0)
24 {
25 std::unique_lock<std::mutex> ul(m_mutex);
26 if (!timeout)
27 {
28 m_condition.wait(
29 ul,
30 [&]()
31 {
32 if (!any)
33 {
34 return false;
35 }
36 return true;
37 }
38 );
39 }
40 else
41 {
42 if (!any)
43 {
44 std::cv_status status = m_condition.wait_for(ul, std::chrono::milliseconds(timeout));
45 if (status == std::cv_status::timeout)
46 {
47 return {};
48 }
49 }
50 }
51 return std::unique_ptr<T>(any.release());
52 }
53
54 private:
55 std::unique_ptr<T> any;
56 };