QThread: avoid unlock/lock/unlock in ~QThread if state is Finishing
This is a corner-case scenario but valid because we tell users they can destroy the QThread object right after finished() has been emitted. But emitting finished() does not mean the launched thread has actually exited: it may still be in Finishing state for an arbitrarily long time. Completely aside from what else may run from other libraries, we only destroy QThreadStorage and the thread's event dispatcher after finished() has been emitted. This commit avoids the unnecessary mutex unlocking in the destructor, then QThread::wait() locking again, only to unlock yet again so that it can perform the necessary low-level wait calls. The same for the return path: wait() locked again to check the state, then unlocked, only for the destructor to lock again. Now, QThreadPrivate::wait() is responsible for returning with a locked mutex. Change-Id: I87adffb89f275accea18fffd6b4293861ea7cf39 Reviewed-by: Mårten Nordheim <marten.nordheim@qt.io> Reviewed-by: Edward Welbourne <edward.welbourne@qt.io> (cherry picked from commit 6bd271cf74d6d57816531f688c82c51d29f1be91) Reviewed-by: Ahmad Samir <a.samirh78@gmail.com>
This commit is contained in:
parent
90c436dd1e
commit
4f85eed8e3
@ -495,11 +495,8 @@ QThread::~QThread()
|
||||
Q_D(QThread);
|
||||
{
|
||||
QMutexLocker locker(&d->mutex);
|
||||
if (d->isInFinish) {
|
||||
locker.unlock();
|
||||
wait();
|
||||
locker.relock();
|
||||
}
|
||||
if (d->isInFinish)
|
||||
d->wait(locker, QDeadlineTimer::Forever);
|
||||
if (d->running && !d->finished && !d->data->isAdopted)
|
||||
qFatal("QThread: Destroyed while thread is still running");
|
||||
|
||||
|
@ -198,6 +198,8 @@ public:
|
||||
uint stackSize;
|
||||
std::underlying_type_t<QThread::Priority> priority;
|
||||
|
||||
bool wait(QMutexLocker<QMutex> &locker, QDeadlineTimer deadline);
|
||||
|
||||
#ifdef Q_OS_UNIX
|
||||
QWaitCondition thread_done;
|
||||
|
||||
|
@ -837,6 +837,14 @@ bool QThread::wait(QDeadlineTimer deadline)
|
||||
if (d->finished || !d->running)
|
||||
return true;
|
||||
|
||||
return d->wait(locker, deadline);
|
||||
}
|
||||
|
||||
bool QThreadPrivate::wait(QMutexLocker<QMutex> &locker, QDeadlineTimer deadline)
|
||||
{
|
||||
Q_ASSERT(locker.isLocked());
|
||||
QThreadPrivate *d = this;
|
||||
|
||||
while (d->running) {
|
||||
if (!d->thread_done.wait(locker.mutex(), deadline))
|
||||
return false;
|
||||
|
@ -495,6 +495,13 @@ bool QThread::wait(QDeadlineTimer deadline)
|
||||
}
|
||||
if (d->finished || !d->running)
|
||||
return true;
|
||||
return d->wait(locker, deadline);
|
||||
}
|
||||
|
||||
bool QThreadPrivate::wait(QMutexLocker<QMutex> &locker, QDeadlineTimer deadline)
|
||||
{
|
||||
Q_ASSERT(locker.isLocked());
|
||||
QThreadPrivate *d = this;
|
||||
|
||||
++d->waiters;
|
||||
locker.mutex()->unlock();
|
||||
|
Loading…
x
Reference in New Issue
Block a user