Important: Please read the Qt Code of Conduct -

Restarting a QThread

  • I have a question about QThread, start() and quit().

    I have a QThread and a worker object that is run in the QThread via moveToThread(). At some point, the worker object calls a function send() that starts sending data, however at some point I call quit() then wait for it to finish via wait(). What I noticed is that when I start the QThread object again through start(), execution of the thread resumes at the last point where it was stopped. Is this normal behavior?

    How can I reset the thread to the state it was at creation along with the worker object?

    Is the only way to do this by stopping the thread normally through quit(), delete the worker object, and create a new worker object, calling moveToThread() on the same thread with the new object before finally calling start? I've tried this way but I get random read access violation errors sometimes; the debugger always jumps to the same line inside the file called xthread:

    inline int _Cnd_broadcastX(_Cnd_t *_Cnd)
    {     // throw exception on failure
      return (_Check_C_return(_Cnd_broadcast(_Cnd)));
    f:\dd\vctools\crt\crtw32\concrt\event.cpp:693: error: Expcetion at 0x237eb5c, code 0xc0000005 read access violation at: 0x0, flags=0x0 (first chance)

    Googling this line of code didn't yield any results. Is this a thread related error?

    Advice appreciated.

  • Lifetime Qt Champion


    Can you show how you implement your worker object and thread handling ?

  • Moderators

    @Nubcake said in Restarting a QThread:

    How can I reset the thread to the state it was at creation along with the worker object?

    Well, QThread::quit() alone doesn't do anything to your worker object, so it remembers its last state.

    Implement an initialization function in your worker object, and make sure this function is called (in the correct thread!) when you start() the thread.

    EDIT 1: To clarify, quit() stops the thread's event loop. That's all.
    EDIT 2: Actually, why do you need to quit the thread? Could you just leave the thread running permanently, and implement a state machine in your worker?

Log in to reply