From 9e32306daea5578ac5cff1424678da25e2a158af Mon Sep 17 00:00:00 2001 From: David Faure Date: Sat, 29 Mar 2025 09:36:36 +0100 Subject: [PATCH] QTestLib: fix race on QElapsedTimers from WatchDog thread The WatchDog thread calls printTestRunTime() which reads the two timers, created and started in the main thread. Pick-to: 6.9 6.8 6.5 Change-Id: I1a337648fddf87190075b7902311544d0ab21ac3 Reviewed-by: Marc Mutz --- src/testlib/qtestlog.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/testlib/qtestlog.cpp b/src/testlib/qtestlog.cpp index 2bde5a94eca..3938c9a85f8 100644 --- a/src/testlib/qtestlog.cpp +++ b/src/testlib/qtestlog.cpp @@ -69,6 +69,7 @@ static void saveCoverageTool(const char * appname, bool testfailed, bool install #endif } +Q_CONSTINIT static QBasicMutex elapsedTimersMutex; // due to the WatchDog thread Q_CONSTINIT static QElapsedTimer elapsedFunctionTime; Q_CONSTINIT static QElapsedTimer elapsedTotalTime; @@ -320,7 +321,10 @@ namespace QTest { void QTestLog::enterTestFunction(const char* function) { - elapsedFunctionTime.start(); + { + QMutexLocker locker(&elapsedTimersMutex); + elapsedFunctionTime.start(); + } if (printAvailableTags) return; @@ -548,8 +552,11 @@ void QTestLog::addBenchmarkResults(const QList &results) void QTestLog::startLogging() { - elapsedTotalTime.start(); - elapsedFunctionTime.start(); + { + QMutexLocker locker(&elapsedTimersMutex); + elapsedTotalTime.start(); + elapsedFunctionTime.start(); + } for (auto &logger : QTest::loggers->allLoggers()) logger->startLogging(); QTest::oldMessageHandler = qInstallMessageHandler(QTest::messageHandler); @@ -767,11 +774,13 @@ bool QTestLog::installedTestCoverage() qint64 QTestLog::nsecsTotalTime() { + QMutexLocker locker(&elapsedTimersMutex); return elapsedTotalTime.nsecsElapsed(); } qint64 QTestLog::nsecsFunctionTime() { + QMutexLocker locker(&elapsedTimersMutex); return elapsedFunctionTime.nsecsElapsed(); }