问题
currently I need to implement a multi-threaded algorithm based on Qt. Maybe I should try to extend QThread
.
But before that, I'd like to ask, if I can just use two QTimer
s timer1
, timer2
, and connect their timeout signal to the threads respectively, to implement a "fake" multi-threaded program?
回答1:
You can connect the timeout() signal of QTimer
to the appropriate slots, and call start()
. From then on, the timers will emit the timeout() signals at constant intervals. But the two timers are run on the main thread and in the main event loop. So you can not call it multithreaded. Because the two slots do not run simultaneously. They run one after an other and if one blocks the main thread, the other will never get called.
You can have a real multithreaded application by having some classes for different tasks that should be done concurrently and use QObject::moveToThread
to change the thread affinity for the object :
QThread *thread1 = new QThread();
QThread *thread2 = new QThread();
Task1 *task1 = new Task1();
Task2 *task2 = new Task2();
task1->moveToThread(thread1);
task2->moveToThread(thread2);
connect( thread1, SIGNAL(started()), task1, SLOT(doWork()) );
connect( task1, SIGNAL(workFinished()), thread1, SLOT(quit()) );
connect( thread2, SIGNAL(started()), task2, SLOT(doWork()) );
connect( task2, SIGNAL(workFinished()), thread2, SLOT(quit()) );
//automatically delete thread and task object when work is done:
connect( thread1, SIGNAL(finished()), task1, SLOT(deleteLater()) );
connect( thread1, SIGNAL(finished()), thread1, SLOT(deleteLater()) );
connect( thread2, SIGNAL(finished()), task2, SLOT(deleteLater()) );
connect( thread2, SIGNAL(finished()), thread2, SLOT(deleteLater()) );
thread1->start();
thread2->start();
Note that Task1
and Task2
inherit from QObject
.
来源:https://stackoverflow.com/questions/24357986/can-i-use-qtimer-to-implement-a-multthreaded-algorithm