Qt 并行计算 Concurrent Run的翻译
資料來(lái)源:https://doc.qt.io/qt-5/qtconcurrentrun.html
Concurrent Run的簡(jiǎn)介:
QtConcurrent::run() 是開(kāi)啟單獨(dú)一個(gè)線程來(lái)運(yùn)行。返回值可以通過(guò)QFuture API來(lái)調(diào)取。
在單獨(dú)的線程中運(yùn)行:
QtConcurrent::run();
run()函數(shù)將在默認(rèn)的QThreadPool 中單獨(dú)一個(gè)線程來(lái)運(yùn)行。可以通過(guò)QFuture和QFutureWatcher 類來(lái)查看此函數(shù)run()運(yùn)行的狀態(tài)。
可以專門開(kāi)設(shè)線程池(pool),如下:
extern void aFunction(); QThreadPool pool; QFuture<void> future = QtConcurrent::run(&pool, aFunction);run()函數(shù)中的參數(shù)傳遞:
例如:
當(dāng)run函數(shù)運(yùn)行的時(shí)候,這些參數(shù)將加載到線程中來(lái)運(yùn)行,
函數(shù)值的返回:
值的返回是通過(guò)QFuture 來(lái)實(shí)現(xiàn)的:
extern QString functionReturningAString(); QFuture<QString> future = QtConcurrent::run(functionReturningAString); ... QString result = future.result();有參數(shù)情況下:
extern QString someFunction(const QByteArray &input);QByteArray bytearray = ...;QFuture<QString> future = QtConcurrent::run(someFunction, bytearray); ... QString result = future.result();注意: QFuture::result() 函數(shù)將阻塞,一直等到result結(jié)果出來(lái)。可以通過(guò)QFutureWatcher 來(lái)獲取 執(zhí)行完畢和計(jì)算結(jié)果的通知。
run函數(shù)的其他特性:
使用成員函數(shù):
QtConcurrent::run() 同樣接受指向成員函數(shù)的指針。這樣,run函數(shù)的第一個(gè)參數(shù)可以是指向常量的指針,或者指向一個(gè)類的對(duì)象。
如果傳遞是常量,通常是調(diào)入常量處理的函數(shù)指針。
如果傳遞是指針,同時(shí)是跳入非常量處理的函數(shù)指針。
例如:通過(guò)調(diào)入QByteArray::split() (a const member function) 在單獨(dú)一個(gè)線程中處理:
// call 'QList<QByteArray> QByteArray::split(char sep) const' in a separate thread QByteArray bytearray = "hello world"; QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ','); ... QList<QByteArray> result = future.result();調(diào)入Calling a non-const member 函數(shù)如下:
// call 'void QImage::invertPixels(InvertMode mode)' in a separate thread QImage image = ...; QFuture<void> future = QtConcurrent::run(&image, &QImage::invertPixels, QImage::InvertRgba); ... future.waitForFinished(); // At this point, the pixels in 'image' have been inverted支持使用Lamdba 函數(shù)如下:
QFuture<void> future = QtConcurrent::run([=]() {// Code in this block will run in another thread }); ...本篇翻譯完畢!
有關(guān)并行計(jì)算的應(yīng)用,請(qǐng)看Qt并行計(jì)算圓周率示例
總結(jié)
以上是生活随笔為你收集整理的Qt 并行计算 Concurrent Run的翻译的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Qt 多线程TCP服务端一键关闭所有客户
- 下一篇: Qt 并行计算圆周率示例