1. 主文件
#include "QtAsync.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtAsync w;
w.show();
return a.exec();
}
2. 窗口类
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtAsync.h"
#include "CDurationTest.h"
class QtAsync : public QMainWindow
{
Q_OBJECT
public:
QtAsync(QWidget *parent = Q_NULLPTR);
~QtAsync();private:
Ui::QtAsyncClass ui;
CDurationTest* test;
};
#include "QtAsync.h"
#include <QTimer>
QtAsync::QtAsync(QWidget *parent) : QMainWindow(parent)
{
ui.setupUi(this); QTimer::singleShot(10, this, [this]() {
test = new CDurationTest;
});
}
QtAsync::~QtAsync()
{
delete test;
test = nullptr;
}
3. 工作类
#pragma once
class CDurationTest
{
public:
CDurationTest();
};
#include "CDurationTest.h"
#include <chrono>
#include <functional>
#include <future>
#include <iostream>
#include <thread>
#include <QCoreApplication>
bool b = false;
CDurationTest::CDurationTest()
{
std::promise<int> promiseObj;
std::future<int> futureObj = promiseObj.get_future();
std::thread thrd([](std::promise<int>& pr)
{
for (int i = 0; i < 10000; i++)
{
std::cout << i + 1 << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(20));
}
b = true;
pr.set_value(10000);
}, std::ref(promiseObj));
thrd.detach();
while (!b)
{
QCoreApplication::instance()->processEvents();
}
b = false;
std::cout << futureObj.get() << std::endl;
}