T102 Don't try to wait for a worker to finish while holding a lock

on the mutex that protects its finished flag, as it will deadlock.
This commit is contained in:
Mathew Sutcliffe
2017-07-04 23:06:59 +01:00
parent 7317ddd155
commit fdbfda848f
2 changed files with 10 additions and 4 deletions

View File

@@ -75,7 +75,13 @@ namespace BlackCore
m_enabled = false; m_enabled = false;
if (!CThreadUtils::isCurrentThreadObjectThread(this)) if (!CThreadUtils::isCurrentThreadObjectThread(this))
{ {
doIfNotFinished([this] { this->abandonAndWait(); }); std::promise<void> promise;
doIfFinishedElse([&promise] { promise.set_value(); }, [&promise, this]
{
this->then([&promise] { promise.set_value(); });
this->abandon();
});
promise.get_future().wait();
} }
} }

View File

@@ -134,7 +134,7 @@ namespace BlackMisc
} }
//! Executes some code (in the caller's thread) if the task has not finished. //! Executes some code (in the caller's thread) if the task has not finished.
//! \threadsafe //! \threadsafe But the functor will deadlock if it waits for the task to finish.
template <typename F> template <typename F>
void doIfNotFinished(F functor) const void doIfNotFinished(F functor) const
{ {
@@ -142,8 +142,8 @@ namespace BlackMisc
if (! m_finished) { functor(); } if (! m_finished) { functor(); }
} }
//! Executes some code (in the caller's thread) if the task has not finished and some different code if it has finished. //! Executes some code (in the caller's thread) if the task has finished and some different code if it has not finished.
//! \threadsafe //! \threadsafe But the elseFunctor will deadlock if it waits for the task to finish.
template <typename F1, typename F2> template <typename F1, typename F2>
void doIfFinishedElse(F1 ifFunctor, F2 elseFunctor) const void doIfFinishedElse(F1 ifFunctor, F2 elseFunctor) const
{ {