QtConcurrent 应用
#include "QDebug"
#include "QThread"
#include "QTimer"
#include "QtConcurrent/QtConcurrent"
#include "QRunnable"
void myclass::RDPrintf(QString str)
{
int io=0;
while( 9 ) {
qDebug()<<"DPrintf"<<str<<QDateTime::currentMSecsSinceEpoch();
for(io=0;io<1000000;io++);
QThread::msleep(1);
//直接调用this->ui->label->setText会出错,因不同线程 ,只能用 QMetaObject::invokeMethod 方法
//this->ui->label->setText(QString::asprintf("Thread %ld",QDateTime::currentMSecsSinceEpoch()));
QMetaObject::invokeMethod( this->ui->label, "setText",
Q_ARG(QString, QString::asprintf("Thread %ld",QDateTime::currentMSecsSinceEpoch())) );
}
}
long DPrintf(QString str)
{
qDebug()<<"DPrintf"<<str<<QDateTime::currentMSecsSinceEpoch();
return QDateTime::currentMSecsSinceEpoch();
}
......
QThreadPool *pool = new QThreadPool;
pool->setMaxThreadCount(100);
for(int i=0;i<100;i++) {
// QFuture<void> fut1 =
//非类方法调用。
QtConcurrent::run( pool, ::DPrintf, QString::asprintf("Thread %0.2d",i) );
// 调用类方法时,被调用的方法不能更新UI,如果更新UI会出现异常,因UI更新线程与之为不同线程
// 更新UI可以通过 QMetaObject::invokeMethod
QtConcurrent::run( pool, this, myclass::RDPrintf, QString::asprintf("Thread %0.2d",i) );
}
......
......
QFuture<long> tef = QtConcurrent::run(::DPrintf, QString("Thread 2"));
tef.waitForFinished(); //等线程结束并返回值
qDebug()<<"tef"<<tef.resultAt(0)<<tef.result();......