代码之家  ›  专栏  ›  技术社区  ›  Megidd

Qt异步调用:如何在异步调用完成其任务后运行某些内容

  •  1
  • Megidd  · 技术社区  · 6 年前

    我有下面这样的代码来执行异步调用:

    QMetaObject::invokeMethod(this, "endSelectionHandling", Qt::QueuedConnection);
    

    我想这样修改代码:

    QMetaObject::invokeMethod(this, "endSelectionHandling", Qt::QueuedConnection);
    
    // I want to add statements here which depend on the result of the above async call.
    // How can I wait for the above async call to finish its jobs?
    

    我如何才能等待Qt-asycn呼叫完成工作?有更好的方法吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Azeem Rob Hyndman    6 年前

    在您的问题中,看起来您根本不需要异步调用,因为您在将结果设为异步调用之后正在等待结果。

    但是,如果您之间有一些代码,您可以使用C++ 11。 std::async 异步调用函数,然后等待 std::future 无论何时何地,你在做其他事情后需要它的结果。

    下面是一个例子:

    #include <iostream>
    #include <future>
    #include <thread>
    #include <chrono>
    
    #define LOG()    std::cout << __func__ << " : "
    
    void test()
    {
        LOG() << "IN\n";
    
        using namespace std::chrono_literals;
        std::this_thread::sleep_for( 1s );
    
        LOG() << "OUT\n";
    }
    
    int main()
    {
        LOG() << "Calling test()...\n";
    
        auto f = std::async( std::launch::async, test );
    
        LOG() << "Running test()...\n";
    
        // ...                             ...
        // ... You can do other stuff here ...
        // ...                             ...
    
        f.wait(); // Blocking call to wait for the result to be available
    
        LOG() << "Exiting...\n";
    
        return 0;
    }
    

    输出如下:

    main : Calling test()...
    main : Running test()...
    test : IN
    test : OUT
    main : Exiting...
    

    下面是一个实例: https://ideone.com/OviYU6

    更新 :

    但是,在Qt领域中,您可能需要使用 QtConcurrent::run QFuture 以Qt方式做事。

    下面是一个例子:

    #include <QDebug>
    #include <QtConcurrent>
    #include <QFuture>
    #include <QThread>
    
    #define LOG()    qDebug() << __func__ << ": "
    
    void test()
    {
        LOG() << "IN";
    
        QThread::sleep( 1 );
    
        LOG() << "OUT";
    }
    
    int main()
    {
        LOG() << "Calling test()...";
    
        auto f = QtConcurrent::run( test );
    
        LOG() << "Running test()...";
    
        // ...                             ...
        // ... You can do other stuff here ...
        // ...                             ...
    
        f.waitForFinished(); // Blocking call to wait for function to finish
    
        LOG() << "Exiting...";
    
        return 0;
    }
    

    输出如下:

    main:正在调用test()。。。
    main:正在运行test()。。。
    测试:在
    测试:OUT
    主要:退出…