Does QThread::quit() immediately end the thread or does it wait until returning to the event loop?

前端 未结 2 1285
天命终不由人
天命终不由人 2021-01-02 05:24

There are a lot of Qt multi-threading tutorials out there that state that a QThread can be stopped safely using the following two lines.

qthread         


        
2条回答
  •  执笔经年
    2021-01-02 06:09

    In case, if you want to use Qt's builtin facility then try QThread::requestInterruption().

    Main thread

    struct X {
      QThread m_Thread; 
      void Quit ()
      {
        m_Thread.quit();
        m_Thread.requestInterruption();
      }
    };
    

    Some Thread referred by X::m_Thread

    while() {
      if(QThread::currentThread()->isInterruptionRequested())
        return;
      ...
    }
    

    As per the documentation:

    void QThread::requestInterruption()

    Request the interruption of the thread. That request is advisory and it is up to code running on the thread to decide if and how it should act upon such request. This function does not stop any event loop running on the thread and does not terminate it in any way.

提交回复
热议问题