32 lines
700 B
C++
32 lines
700 B
C++
|
#pragma once
|
||
|
#include <base/types.hpp>
|
||
|
|
||
|
namespace base {
|
||
|
|
||
|
/// An asynchronous version of std::condition_variable.
|
||
|
/// Useful for synchronizing or pausing coroutines.
|
||
|
struct AsyncConditionVariable {
|
||
|
AsyncConditionVariable(asio::any_io_executor exec) : timer(exec) { timer.expires_at(std::chrono::steady_clock::time_point::max()); }
|
||
|
|
||
|
void NotifyOne() { timer.cancel_one(); }
|
||
|
|
||
|
void NotifyAll() { timer.cancel(); }
|
||
|
|
||
|
template <class Predicate>
|
||
|
Awaitable<void> Wait(Predicate pred) {
|
||
|
while(!pred()) {
|
||
|
try {
|
||
|
co_await timer.async_wait(asio::deferred);
|
||
|
} catch(...) {
|
||
|
// swallow errors
|
||
|
}
|
||
|
}
|
||
|
co_return;
|
||
|
}
|
||
|
|
||
|
private:
|
||
|
SteadyTimer timer;
|
||
|
};
|
||
|
|
||
|
} // namespace base
|