QThreadPool 强制停止在 qt cpp 中

QThreadPool force stop in qt cpp

本文关键字:qt cpp QThreadPool      更新时间:2023-10-16

我已经创建了Qthreadpool。 我想从队列中删除所有任务。代码如下。

void MainWindow::startThread()
{
   thread= new QThradPool(this);
   thread->setMaxThreadcount(1);
   hello = new HelloWordTask();
   thread->start(hello);
}
void MainWindow::stopThread()
{
  thread->clear();
  delete thread;
  delete hello;
  // but current task is not stopping. until it is finished. i want to stop it 
   immediately .
}
void HelloWordTask::run()
{
  // function which takes time
}

这通常是不可能的。有些QFuture - 不是QtConcurrent::run返回的那些 - 是可以取消的。如果您使用的是 QtConcurrent::run 或提交通用QRunnable,则需要使其可取消。这个答案提供了一种生成在线程池上运行的可取消未来的方法。然后,您需要跟踪这些期货并取消任何正在进行的期货。

一般来说,不需要动态创建线程池 - 只需按值存储它。一旦你使用了QFuture接口,也不需要管理任务的生存期:期货是这个对象的句柄,一旦最后一个对象消失,任务对象就会被释放。

class HelloWorldTask : RunControllableTask<void> {
  // see https://stackoverflow.com/a/16729619/1329652
  ...
};
class MainWindow : public QMainWindow {
  QThreadPool m_pool;
  QVector<QFuture<void>> m_futures;
public:
  explicit MainWindow(QWidget * parent = {}) : QMainWindow(parent) {
    m_pool.setMaxThreadCount(1);
  }
  void startTask() {
    auto future = TaskExecutor::run(new HelloWorldTask());
    m_futures.push_back(future);
  }
  void stopAllTasks() {
    m_pool.cancel();
    for (auto &future : m_futures)
      future.cancel();
    while (!m_futures.isEmpty())
      m_futures.takeLast().waitForFinished(); // this will free the task too!
    Q_ASSERT(!m_pool.activeThreadCount());
  }
  ~MainWindow() override {
    stopAllTasks();
  }
};

您也可以使用 future 接口从任务中线程安全地返回数据!