Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    How to stop a function in one thread?

    General and Desktop
    2
    2
    1722
    Loading More Posts
    • 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.
    • M
      MonkeyTang last edited by

      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. )

      1 Reply Last reply Reply Quote 0
      • SGaist
        SGaist Lifetime Qt Champion last edited by

        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

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        1 Reply Last reply Reply Quote 0
        • First post
          Last post