Qt 如何并发异步调用?
QT += core concurrent widgets
template<typename T, typename Handler>
void await(const QFuture<T> &future, QObject *context, Handler handler)
{
auto *watcher = new QFutureWatcher<T>(context);
QObject::connect(watcher, &QFutureWatcherBase::finished,
context, [watcher, handler { std::move(handler) }]() {
handler(watcher->result());
watcher->deleteLater();
});
watcher->setFuture(future);
}
template<typename Handler>
auto async(Handler handler)
{
// 默认使用全局线程池,线程池大小与使用者电脑相关。
return QtConcurrent::run(QThreadPool::globalInstance(),handler);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 使用 async 启动异步函数
auto func = async([](){
auto total{0ull};
for(auto i = 0;i < 10000000;i++){
total += i;