How to stop a function in one thread?



  • Here's my case:
    I have one function, which will be a long time running,not a loop. But so many steps to do in such a function. So I move this test function to one thread. And also, I need this test function stop immediately when stop button clicked in the main thread, no matter which step runs in the test function. So I do this purpose bellow:

    @
    (init thread)
    threadDaqCtrl = new QThread();
    daqValveCtrl->moveToThread(threadDaqCtrl);
    @
    @
    (when stop button clicked, terminate this thread,the function in this thread must stop.and restart this thread,wait for second calling.)
    threadDaqCtrl->terminate();
    threadDaqCtrl->start();
    @

    So problem comes:

    1. this action not so good, is there any way better than terminate thread directly?

    2. the program will crash when start button clicked for calling the test function next time. How to solve this?
      (this only happens in win7, XP and win8 are ok,no crash! my platform is: QT4.8.3+VS2010sp1. )


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Indeed, terminating a thread like that also means that it's state is unknown so you should not reuse it like that.

    I you have such a long function, juste add a check between each step like

    @if (!continue)
    return;
    @

    or something better and add a function to set continue to false when needing to stop. So now your thread can end cleanly and you can restart it.

    Hope it helps


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.