QT不阻塞UI的方式

方法1:QtConcurrent

#include <QtConcurrent>
#include <QFuture>
#include <QFutureWatcher>
#include <QDebug>

void longRunningTask() {
    // 模拟耗时操作
    QThread::sleep(5);
}

void startTask() {
    QFuture<void> future = QtConcurrent::run(longRunningTask);
    QFutureWatcher<void> *watcher = new QFutureWatcher<void>();
    
    QObject::connect(watcher, &QFutureWatcher<void>::finished, []() {
        qDebug() << "Task finished, update UI here.";
        // 在这里更新UI
    });

    watcher->setFuture(future);
}

方法2:QEventLoop

QEventLoop loop;
QTimer::singleShot(milliseconds, &loop, &QEventLoop::quit);
loop.exec();

方法3:thread

std::thread th1(function);
th1.detach();

方法4:async

#include <iostream>
#include <future>
#include <chrono>

// 模拟一个耗时的计算任务
int longRunningTask(int id, int duration) {
    std::cout << "Task " << id << " started, will take " << duration << " seconds." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(duration)); // 模拟耗时任务
    std::cout << "Task " << id << " completed." << std::endl;
    return id * duration;  // 返回一些计算结果
}

int main() {
    // 使用std::async启动两个异步任务
    std::future<int> result1 = std::async(std::launch::async, longRunningTask, 1, 3);
    std::future<int> result2 = std::async(std::launch::async, longRunningTask, 2, 2);

    std::cout << "Main thread continues to run..." << std::endl;

    // 在主线程做其他事情
    for (int i = 0; i < 5; ++i) {
        std::cout << "Main thread working..." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    // 获取异步任务的结果
    int value1 = result1.get();  // 这时如果任务尚未完成,主线程会阻塞在此
    int value2 = result2.get();

    std::cout << "Result of task 1: " << value1 << std::endl;
    std::cout << "Result of task 2: " << value2 << std::endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex1_Code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值