Это моя попытка, но Честно говоря, я понятия не имею, что делаю
Код: Выделить всё
template
class ConditionVariableAwaiter : public boost::asio::awaitable {
public:
ConditionVariableAwaiter(std::condition_variable& cv, std::mutex& mtx, std::function && ready, const std::chrono::seconds timeout = std::chrono::seconds(0))
: _cv(cv), _mutex(mtx), _ready(std::move(ready)), _handle(nullptr), _timeout(timeout) {}
ConditionVariableAwaiter(ConditionVariableAwaiter && other) noexcept :
_cv(std::move(other._cv)),
_mutex(std::move(other._cv)),
_ready(std::move(other._ready)),
_handle(std::move(other._handle)),
_timeout(std::move(other._timeout)) {}
ConditionVariableAwaiter &operator=(ConditionVariableAwaiter && other) noexcept {
_cv = std::move(other._cv);
_mutex = std::move(other._cv);
_ready = std::move(other._ready);
_handle = std::move(other._handle);
_timeout = std::move(other._timeout);
}
ConditionVariableAwaiter(const ConditionVariableAwaiter & other) = delete;
ConditionVariableAwaiter &operator=(const ConditionVariableAwaiter & other) = delete;
bool await_ready() const noexcept {
return _ready();
}
void await_suspend(std::coroutine_handle handle) {
std::unique_lock lock(_mutex);
_handle = handle;
if (_timeout.count() == 0) {
_cv.wait(lock, [this] { return _ready(); });
_handle.resume();
}
else {
if (_cv.wait_for(lock, _timeout, [this] { return _ready(); })) {
_handle.resume();
}
else {
_timedOut = true;
_handle.resume();
}
}
}
bool await_resume() const noexcept {
return _timedOut;
}
void notify() {
std::lock_guard lock(_mutex);
_cv.notify_all();
if (_handle && _ready()) {
_handle.resume();
}
}
bool timedOut() const {
return _timedOut;
}
private:
std::condition_variable& _cv;
std::mutex& _mutex;
std::function _ready;
std::coroutine_handle _handle;
std::chrono::seconds _timeout;
bool _timedOut = false;
};
Код: Выделить всё
error: use of deleted function ‘boost::asio::awaitable::awaitable(const boost::asio::awaitable&) [with T = std::optional; Executor = boost::asio::any_io_executor]’
[build] 143 | co_await awaiter;
Код: Выделить всё
ConditionVariableAwaiter awaiter(_cv, _mutex, [this] { return !_map.empty() || _cancelled; });
Подробнее здесь: https://stackoverflow.com/questions/785 ... n-variable