【问题标题】:Clean up QThread after calling quit()调用 quit() 后清理 QThread
【发布时间】:2024-01-08 09:37:01
【问题描述】:

我有问题。如果我调用 Abort(),运行函数将返回,而 complexMath 实例没有足够的时间进行清理。

我想要的是,在调用 Abort() 之后,complexMath 实例有足够的时间自行关闭,在返回之前清除所有待处理的信号和槽(在 complexMath 内部,它也有自己的信号和槽)。

void MyThread::Go(){
  start();
}

void MyThread::Abort(){
  emit stopNow();
  quit();
}

void MyThread::run(){
  ComplexMath * complexMath = new ComplexMath();
  connect( complexMath, SIGNAL(OnCalculation(qint)), this, SLOTS(PartialOutput(qint)) );
  connect( this, SIGNAL(stopNow()), complexMath, SLOTS(deleteLater());
  exec();
}

void MyThread::PartialOutput(qint data){
  qDebug() << data;
}

谢谢!

【问题讨论】:

    标签: qt exec signals-slots qthread quit


    【解决方案1】:

    我认为你可以摆脱 stopNow 信号:

    void MyThread::Abort(){
      quit();
    }
    
    void MyThread::run(){
      ComplexMath * complexMath = new ComplexMath();
      connect( complexMath, SIGNAL(OnCalculation(qint)), this, SLOTS(PartialOutput(qint)) );
      exec();
      // Any code here will be run after the thread quits, and the event loop stops
      deleteLater();
    }
    

    【讨论】: