QT多线程选项

来源:互联网 发布:飞天侠淘宝干嘛的 编辑:程序博客网 时间:2024/05/20 05:45
QT多线程选项:


1、QThread subclassing


MyThread::MyThread()
{
// In creating thread
}


MyThread::~MyThread()
{
// In creating thread
}


MyThread::run()
{
// In creating thread
// Don't use this as parent
// Make sure all objects in thread are
// deleted before the thread is done
}


2、QThread worker threads


class MyObject : public QObject
{
Q_OBJECT
public slots:
void doStuff() { /* process here */ emit done(); }

signals:
void done();
}


QThread workerThread;
MyObject object;
object.movetoThread(&workerThread);
connect(workerThread, started, object, doStuff);
connect(object, done, workerThread, quit);
workerThread.start();


3、QRunnable and thread pools


class Worker : public QRunnable
{
void run() { /* process workload here */ }
}


Worker* worker = new Worker(itemToWorkOn);
QThreadPool::globalInstance()->start(worker);


4、QtConcurrent::run


QList<int> complicatedDBSearch();


QFutureWatcher<QList<int> > watcher;
connect(watcher, finished, someObject, dbListReady);


QFuture<QList<int> > idList = QtConcurrent::run(complicatedDBSearch);


watcher.setFuture(idList);


5、QtConcurrent maps and filters


qreal studentAverage(int studentID);
QFuture<qreal> future = QtConcurrent::mapped(allStudents, studentAverage);
qDebug() << future.results();


void add(qreal& g1, qreal g2) { g1 += g2; }
QFuture<qreal> averages = QtConcurrent::mappedReduced(allStudents, studentAverage, add);
schoolAverage = averages.results()[0] / studentCount;


void idToHtml(QString s&, int id) { ... }
bool studentsNamedBo(int id) {
return getStudentName(id).startsWith("Bo");
}
QFuture<qreal> webPage = QtConcurrent::filteredReduced(allStudents, studentBo, idToHtml);
html = htmlTop + webPage.results()[0] + htmlBottom;






Recommendations:


QThread subclassing: pure processing
QThread worker: "Normal" MT Qt code
QRunable and QThreadPool: For separate worker chunks
Map-reduce and filter-reduce: When the problems allows it
QtConcurrent: Whenever possible
0 0
原创粉丝点击