QT开发中文网

有一个函数需要的他的返回值,但执行的时候阻塞主线程,导致界面卡顿,用c++ 的异步和回调机制,实现子线程里运行函数,当有返回值时候,自动通知主线程,并显示

好的,以下是资深软件工程师可能会给出的解答:

首先,我们可以使用C++11标准库中提供的std::thread来创建一个子线程,并在其中执行需要返回值的函数。代码示例如下:

#include <iostream>
#include <thread>
#include <future>

int func()
{
    // 模拟需要一定时间才能返回结果的函数
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

int main()
{
    std::future<int> result = std::async(std::launch::async, func);
    // 等待子线程完成并获取返回值
    int value = result.get();
    std::cout << "The result is: " << value << std::endl;

    return 0;
}

上述代码中,std::async函数用于在新线程中执行func()函数,并返回一个std::future<int>类型的对象,该对象表示将来会有一个整数类型的返回值。调用该对象的成员函数get()可以等待子线程完成并获取其返回值。

接下来,我们需要将上述代码应用到GUI程序中。假设我们使用Qt编写GUI程序,那么可以在主线程中创建一个QFutureWatcher对象,并连接其finished()信号到槽函数,在槽函数中获取并显示异步操作的结果。代码示例如下:

#include <QtWidgets/QApplication>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLabel>
#include <QtCore/QFutureWatcher>
#include <QtCore/QThread>

int func()
{
    // 模拟需要一定时间才能返回结果的函数
    QThread::sleep(2);
    return 42;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QPushButton button("Run");
    QLabel label("Result: ");
    QFutureWatcher<int> watcher;

    QObject::connect(&button, &QPushButton::clicked, [&watcher]() {
        // 在新线程中执行func()函数,并将返回值传递给QFutureWatcher对象
        watcher.setFuture(QtConcurrent::run(func));
    });

    QObject::connect(&watcher, &QFutureWatcher<int>::finished, [&label, &watcher]() {
        // 在主线程中获取异步操作的结果,并显示在标签上
        int value = watcher.result();
        label.setText("Result: " + QString::number(value));
    });

    button.show();
    label.show();

    return app.exec();
}

上述代码中,我们创建了一个QPushButton和一个QLabel来分别表示运行异步操作和显示其结果。当用户点击按钮时,我们通过QtConcurrent库中的QtConcurrent::run()函数在新线程中执行func()函数,并将其返回值传递给QFutureWatcher对象。同时,我们连接了QFutureWatcher对象的finished()信号到槽函数,在该槽函数中获取并显示异步操作的结果。

注意,在使用Qt进行GUI编程时,不要在子线程中直接更新UI界面,因为这可能会导致程序崩溃或者出现奇怪的错误。正确的做法是使用信号与槽机制,在主线程中更新UI界面。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=1836

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?