QT最大线程并发

发布时间:2023年12月18日

声明一个处理函数;int timeTask();

头文件:

#include <QtConcurrent>
#include <QFuture>

并发处理改函数的任务,直到处理完成:

QFuture<int> ft = QtConcurrent::run(this, &ch72_concurrent::timeTask);

    while (!ft.isFinished())
    {
        QApplication::processEvents(QEventLoop::AllEvents, 30);
    }

带参数的函数:

将参数写在后面

QFuture<int> ft = QtConcurrent::run(this, &ch74::timeTask, num1, num2);

通过QFutureWatcher获取返回值:

QFutureWatcher<int>* fw = new QFutureWatcher<int>;

    connect(fw, &QFutureWatcher<int>::finished, [&]{
        qDebug() << "QFutureWatcher finished";
        qDebug() << "result = " << fw->result();
        });

    QFuture<int> ft = QtConcurrent::run(this, &ch74::timeTask, num1, num2);
    fw->setFuture(ft);

    while (!ft.isFinished())
    {
        QApplication::processEvents(QEventLoop::AllEvents, 30);
    }

完整代码

#include "ch74.h"
#include <QDebug>
#include <QtConcurrent>
#include <QFuture>
#include <QFutureWatcher>


ch74::ch74(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
}

ch74::~ch74()
{}

int ch74::timeTask(int& num1, int& num2)
{
    for (int i = 0; i < 1000; i++)
    {
        num1++;
        num2++;
        qDebug() << num1;
        qDebug() << num2;
    }

    return num1 + num2;
}

void ch74::on_pushButton_clicked()
{
    int num1 = 0;
    int num2 = 0;

    QFutureWatcher<int>* fw = new QFutureWatcher<int>;

    connect(fw, &QFutureWatcher<int>::finished, [&]{
        qDebug() << "QFutureWatcher finished";
        qDebug() << "result = " << fw->result();
        });

    QFuture<int> ft = QtConcurrent::run(this, &ch74::timeTask, num1, num2);
    fw->setFuture(ft);

    while (!ft.isFinished())
    {
        QApplication::processEvents(QEventLoop::AllEvents, 30);
    }
}

文章来源:https://blog.csdn.net/weixin_38241876/article/details/135044300
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。