如何在线程完成后运行我的Qt函数?

时间:2016-09-05 16:14:28

标签: c++ multithreading qt qtconcurrent

void MainWindow::on_pushButton_clicked()
{
    QFuture<int> future = QtConcurrent::run(identify);  //Thread1
    if (future.isFinished())
    {
       //DoSomething();    
    }
}

我有这个代码。我想在识别功能运行完毕后运行DoSomething()函数。有可能吗?

2 个答案:

答案 0 :(得分:7)

您可以将QFuture对象传递给QFutureWatcher并将其finished()信号连接到函数或广告位DoSomething()

例如:

void MainWindow::on_pushButton_clicked()
{
    QFuture<int> future = QtConcurrent::run(identify); //Thread1
    QFutureWatcher<int> *watcher = new QFutureWatcher<int>(this);
           connect(watcher, SIGNAL(finished()), this, SLOT(doSomething()));
    // delete the watcher when finished too
     connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater()));
    watcher->setFuture(future);
}

void MainWindow::DoSomething() // slot or ordinary function
{
    // ...
}   

或者您可以使用嵌套的事件循环来保持GUI响应并使所有内容都在同一个函数中:

void MainWindow::on_pushButton_clicked()
{
    QFuture<int> future = QtConcurrent::run(identify);  //Thread1
    QFutureWatcher<int> watcher;
    QEventLoop loop;
    // QueuedConnection is necessary in case the signal finished is emitted before the loop starts (if the task is already finished when setFuture is called)
    connect(&watcher, SIGNAL(finished()), &loop, SLOT(quit()),  Qt::QueuedConnection); 
    watcher.setFuture(future);
    loop.exec();

    DoSomething();
}

答案 1 :(得分:0)

我喜欢这种通话布局。

auto watcher = new QFutureWatcher<int>(this);
connect(watcher, &QFutureWatcher<int>::finished,
    [watcher, this] ()
{
    watcher->deleteLater();
    auto res = watcher->result();
    // ...
});

watcher->setFuture(QtConcurrent::run(identify, param1, param2));