QThreadPool强制停止在qt cpp中

时间:2018-03-15 09:31:37

标签: c++ qt

我创建了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
}

1 个答案:

答案 0 :(得分:1)

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

一般来说,不需要动态创建线程池 - 只需按值存储即可。一旦你使用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接口来线程安全地从任务返回数据!