From 9095167039592088c10c251b99c4d3ade6a59a8e Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Tue, 7 May 2019 19:54:54 +0200 Subject: [PATCH] thread/*Cond: add wait_for() overload with predicate --- src/lib/nfs/Blocking.hxx | 6 +----- src/thread/PosixCond.hxx | 13 +++++++++++++ src/thread/WindowsCond.hxx | 13 +++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/lib/nfs/Blocking.hxx b/src/lib/nfs/Blocking.hxx index 5d5d707e3..981d1434c 100644 --- a/src/lib/nfs/Blocking.hxx +++ b/src/lib/nfs/Blocking.hxx @@ -60,11 +60,7 @@ public: private: bool LockWaitFinished() noexcept { std::unique_lock lock(mutex); - while (!finished) - if (!cond.wait_for(lock, timeout)) - return false; - - return true; + return cond.wait_for(lock, timeout, [this]{ return finished; }); } /** diff --git a/src/thread/PosixCond.hxx b/src/thread/PosixCond.hxx index d16aa2898..8ab2a3f03 100644 --- a/src/thread/PosixCond.hxx +++ b/src/thread/PosixCond.hxx @@ -105,6 +105,19 @@ public: return wait_for(lock, timeout_us); } + + template + bool wait_for(std::unique_lock &lock, + std::chrono::steady_clock::duration timeout, + P &&predicate) noexcept { + while (!predicate()) { + // TODO: without wait_until(), this multiplies the timeout + if (!wait_for(lock, timeout)) + return predicate(); + } + + return true; + } }; #endif diff --git a/src/thread/WindowsCond.hxx b/src/thread/WindowsCond.hxx index 162a9ac7a..40389512b 100644 --- a/src/thread/WindowsCond.hxx +++ b/src/thread/WindowsCond.hxx @@ -70,6 +70,19 @@ public: &lock.mutex()->critical_section, timeout_ms); } + + template + bool wait_for(std::unique_lock &lock, + std::chrono::steady_clock::duration timeout, + P &&predicate) noexcept { + while (!predicate()) { + // TODO: without wait_until(), this multiplies the timeout + if (!wait_for(lock, timeout)) + return predicate(); + } + + return true; + } }; #endif