From 5a02d30a78991240c3355d863f52b0d376ebf911 Mon Sep 17 00:00:00 2001 From: Corentin Jabot Date: Sun, 20 Jan 2013 13:24:30 +0100 Subject: Add an advisory interruption mechanism to QThread. To ease interruption of long running tasks, a new method QThread::setInterruptionRequested() can be called. The task can check QThread::isInterruptionRequested() and act upon it by stopping itself. These methods are designed to replace the use of a global variable and other hacky ways to stop a task running in another thread. Change-Id: I17622dd60d2262078210e7e4294ad6c53a6dc179 Reviewed-by: Oswald Buddenhagen Reviewed-by: Thiago Macieira --- tests/auto/corelib/thread/qthread/tst_qthread.cpp | 40 +++++++++++++++++++++++ 1 file changed, 40 insertions(+) (limited to 'tests/auto') diff --git a/tests/auto/corelib/thread/qthread/tst_qthread.cpp b/tests/auto/corelib/thread/qthread/tst_qthread.cpp index 1ee628dde5..5cc0e5bdb4 100644 --- a/tests/auto/corelib/thread/qthread/tst_qthread.cpp +++ b/tests/auto/corelib/thread/qthread/tst_qthread.cpp @@ -106,6 +106,8 @@ private slots: void customEventDispatcher(); + void requestTermination(); + #ifndef Q_OS_WINCE void stressTest(); #endif @@ -1345,5 +1347,43 @@ void tst_QThread::quitLock() QVERIFY(exitThreadCalled); } +class StopableJob : public QObject +{ + Q_OBJECT +public: + StopableJob (QSemaphore &sem) : sem(sem) {} + QSemaphore &sem; +public Q_SLOTS: + void run() { + sem.release(); + while (!thread()->isInterruptionRequested()) + QTest::qSleep(10); + sem.release(); + Q_EMIT finished(); + } +Q_SIGNALS: + void finished(); +}; + +void tst_QThread::requestTermination() +{ + QThread thread; + QVERIFY(!thread.isInterruptionRequested()); + QSemaphore sem; + StopableJob *j = new StopableJob(sem); + j->moveToThread(&thread); + connect(&thread, &QThread::started, j, &StopableJob::run); + connect(j, &StopableJob::finished, &thread, &QThread::quit, Qt::DirectConnection); + connect(&thread, &QThread::finished, j, &QObject::deleteLater); + thread.start(); + QVERIFY(!thread.isInterruptionRequested()); + sem.acquire(); + QVERIFY(!thread.wait(1000)); + thread.requestInterruption(); + sem.acquire(); + QVERIFY(thread.wait(1000)); + QVERIFY(!thread.isInterruptionRequested()); +} + QTEST_MAIN(tst_QThread) #include "tst_qthread.moc" -- cgit v1.2.3