Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to terminate a QThread + Worker process
Qt 6.11 is out! See what's new in the release blog

How to terminate a QThread + Worker process

Scheduled Pinned Locked Moved General and Desktop
2 Posts 2 Posters 1.3k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    kovand11
    wrote on last edited by
    #1

    Applying the same solution like in that example ( http://qt-project.org/wiki/QThreads_general_usage ), and assuming that the worker runs indefinitely, how can I elegantly implement the termination of the process.

    For example:
    @
    void Worker::process()
    {
    for (int i = 0; i < 100000; i++)
    {
    qDebug() << i;
    QThread::msleep(1000);
    }
    }
    @

    When I start the thread, it starts counting, but neither quit(), nor terminate() can stop it.

    1 Reply Last reply
    0
    • JKSHJ Offline
      JKSHJ Offline
      JKSH
      Moderators
      wrote on last edited by
      #2

      Hi,

      To stop the process() function, you need to call break; in your for-loop.

      Anyway, QThread + Worker Object is for event-driven programming. Use it if you want to use signals and slots to communicate between threads.

      However, a long for-loop (which is like an infinite loop) is incompatible with event-driven programming. quit() didn't work because it was waiting for your loop to finish running.

      To run a long for-loop in a QThread, you should:

      Subclass QThread.

      DON'T use signals and slots with your QThread subclass.

      Reimplement QThread::run() and put your loop inside it.

      Check QThread::isInterruptionRequested() in your loop, and break if it returns true.

      Call QThread::requestInterruption() to stop your thread.

      @
      class MyThread : public QThread {
      ...

      protected:
      void run() {
      for (int i = 0; i < 100000; i++) {
      if (isInterruptionRequested())
      break;
      qDebug() << i;
      QThread::msleep(1000);
      }
      }
      };
      @

      Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved