Can I use QTimer to implement a multthreaded algorithm?

风格不统一 提交于 2019-12-11 02:28:42

问题


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 QTimers 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!