gpt4 book ai didi

c++ - Qt 异步调用 : how to run something after an async call has finished its job

转载 作者:行者123 更新时间:2023-11-30 03:21:59 28 4
gpt4 key购买 nike

我有如下代码进行异步调用:

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 调用完成它的工作?有没有更好的方法?

最佳答案

在您的问题中,您似乎根本不需要异步调用,因为您在进行异步调用后立即等待结果。

但是,如果中间有一些代码,您可以使用 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::runQFuture以 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 : Calling test()...
main : Running test()...
test : IN
test : OUT
main : Exiting...

关于c++ - Qt 异步调用 : how to run something after an async call has finished its job,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51587091/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com