From 3f207e0b333c6b8f071f6d04cea96eb9c26b0f16 Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Thu, 23 Jan 2020 04:48:56 +0200 Subject: libcamera: thread: Support timeout in wait() function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a parameter to the Thread::wait() function to wait with a timeout. The delay value utils::duration::max() waits forever. Signed-off-by: Laurent Pinchart Reviewed-by: Kieran Bingham Reviewed-by: Niklas Söderlund --- src/libcamera/thread.cpp | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'src/libcamera/thread.cpp') diff --git a/src/libcamera/thread.cpp b/src/libcamera/thread.cpp index 1d0a600a..b613305f 100644 --- a/src/libcamera/thread.cpp +++ b/src/libcamera/thread.cpp @@ -8,6 +8,7 @@ #include "thread.h" #include +#include #include #include #include @@ -155,6 +156,7 @@ private: std::atomic dispatcher_; + std::condition_variable cv_; std::atomic exit_; int exitCode_; @@ -334,6 +336,7 @@ void Thread::finishThread() data_->mutex_.unlock(); finished.emit(this); + data_->cv_.notify_all(); } /** @@ -360,14 +363,33 @@ void Thread::exit(int code) /** * \brief Wait for the thread to finish + * \param[in] duration Maximum wait duration * - * This method waits until the thread finishes, or returns immediately if the - * thread is not running. + * This function waits until the thread finishes or the \a duration has + * elapsed, whichever happens first. If \a duration is equal to + * utils::duration::max(), the wait never times out. If the thread is not + * running the function returns immediately. + * + * \return True if the thread has finished, or false if the wait timed out */ -void Thread::wait() +bool Thread::wait(utils::duration duration) { + bool finished = true; + + { + MutexLocker locker(data_->mutex_); + + if (duration == utils::duration::max()) + data_->cv_.wait(locker, [&]() { return !data_->running_; }); + else + finished = data_->cv_.wait_for(locker, duration, + [&]() { return !data_->running_; }); + } + if (thread_.joinable()) thread_.join(); + + return finished; } /** -- cgit v1.2.1