How to stop function execution



  • Hi,

    I have 2 thread, the first is the main app thread, and the second one is a dedicated thread for time consuming functions.

    My app emit a signal to start a function in the second thread. A waiting message box pop in the window of the first thread.

    My question is how can i cancel the execution of the function in the second thread ?
    I don't want to stop and exit the thread (because i would have to reload a lot of DLLs ), i just want to exit a function (where there is a lot of loops).

    Thx


  • Qt Champions 2016

    Hi
    Often you would teach the actual code how to quit on demand.
    if you have many loops etc then you cant exit cleanly if they are not
    designed to exit premature.

    for (int c=0; c< max && !Terminated; c++ )
    xxx

    Unless u check if to exit then loops will run fully.

    So question is to u want to really cancel the operation or simply just kinda kill the tread? (which u dont as far as i understand)

    So for me it sounds like you want the function to be able to exit and not so much the tread as such.



  • Hi and thank you for helping me,

    Yes that's it, i don't want to stop the thread, only a function.
    Then the second thread wait for a new signal from the main thread.

    I don't want to kill the thread because i'm only creating threads at the begining of my program, the second thread must live until the main thread lives.



  • define a

    private:
    std::atomic_bool m_terminator
    public:
    void stopFunction(){m_terminator=false;}
    

    in the worker of the second thread. and check for its value in the loops as suggested by @mrjj
    When you need to stop the function just call stopFunction from the first thread (being atomic takes care of avoiding race conditions)


  • Qt Champions 2016

    @Zoptune
    So it seems that best route is to learn your long lasting functions to exit when asked?
    Im not 100% sure there is no better way so give it some hours/day to get others opinions :)



  • Thx @VRonin and @mrjj

    I'll do as you said, i think it's the best way :)

    EDIT : i can't set the topic as solved, haven't got the option in the topic tool



  • @Zoptune said in How to stop function execution:

    EDIT : i can't set the topic as solved, haven't got the option in the topic tool

    Due to a change in template you first have to convert to a question, see
    https://forum.qt.io/topic/71830/hitchhiker-s-visual-guide-to-the-qt-forum


Log in to reply
 

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