#include <QtConcurrent>
#include <QFuture>
void worker() {
QFuture<void> future = QtConcurrent::run([this]() {
// 这是一个协程
co_await co_create_future<void>(); // 创建协程
// 协程内部可以执行多线程任务
// 例如:
// co_await performSomeLongRunningJob();
// ...
// 协程执行完毕后,可使用co_return返回值给等待协程的调用方
});
}
void mainLoop() {
// 调用worker()函数
worker();
// 等待worker()协程完成
future.waitForFinished();
}
正式:
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication1.h"
//QFuture类表示异步计算的结果
#include <QFuture>
//QFuture本身不带信号槽,可使用QFutureWatcher进行监控
#include <QFutureWatcher>
//QFutureInterface没有提供文档,出现于Qt源码
//QFuture与QFutureInterface的关系类似std::future与std::promise
//QFutureInterface可用于生成QFuture
//在Qt类实现中,QFuture持有一个QFutureInterface成员
#include <QFutureInterface>
class QtWidgetsApplication1 : public QMainWindow
{
Q_OBJECT
public:
QtWidgetsApplication1(QWidget *parent = nullptr);
~QtWidgetsApplication1();
public slots:
void on_start_clicked();
void on_stop_clicked();
private:
Ui::QtWidgetsApplication1Class ui;
//QFuture本身不带信号槽,可使用QFutureWatcher进行监控
QFutureWatcher<bool> myWatcher;
};
#include "QtWidgetsApplication1.h"
#include <thread>
#include <QThread>
#include <QDebug>
#include <QPushButton>
QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//异步结果
connect(&myWatcher, &QFutureWatcher<bool>::finished, [=] {
if (myWatcher.result()) {
}
else {
}
});
ui.progressBar->setRange(0,100);
ui.progressBar->setValue(0);
connect(&myWatcher, &QFutureWatcher<bool>::progressValueChanged, [=](int value) {
ui.progressBar->setValue(value);
});
connect(&myWatcher, &QFutureWatcher<bool>::progressTextChanged, [=](const QString text) {
ui.label->setText(text);
});
}
QtWidgetsApplication1::~QtWidgetsApplication1()
{
myWatcher.pause();
myWatcher.waitForFinished();
}
void QtWidgetsApplication1::on_stop_clicked()
{
myWatcher.pause();
}
void QtWidgetsApplication1::on_start_clicked()
{
qDebug() << "点击 start" << QThread::currentThread();
if (!myWatcher.isFinished()) {
qDebug() << "老哥,当前任务还没结束,等等呗";
return;
}
QFutureInterface<bool> interface;
interface.reportStarted();
interface.setProgressRange(0, 100);
myWatcher.setFuture(interface.future());
//QFutureInterface是允许拷贝的,里面有一个d指针
std::thread thread([this, interface]() mutable {
qDebug() << "线程开始" << QThread::currentThread();
//使用sleep模拟耗时处理过程
bool result = true;
for (int i = 0; i < 10; i++)
{
//操作前判断是否结束
if (interface.isPaused()) {
//pause后不接收值了
//interface.setProgressValueAndText(0,"Cancel");
result = false;
//不恢复watcher不能收到消息
interface.setPaused(false);
break;
}
//使用sleep模拟耗时处理过程
QThread::msleep(200);
//设置值前判断是否结束
if (interface.isPaused()) {
result = false;
interface.setPaused(false);
break;
}
const int progress = (i + 1) * 10;
interface.setProgressValueAndText(
progress,
QString("progress:%%1").arg(progress));
}
interface.reportResult(result);
interface.reportFinished();
qDebug() << "线程结束" << QThread::currentThread();
});
thread.detach(); //分离不管他了,用future来确保退出
}