我可以使用QTimer来实现多线程算法吗? [英] Can I use QTimer to implement a multthreaded algorithm?

查看:1161
本文介绍了我可以使用QTimer来实现多线程算法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我需要实现基于Qt的多线程算法.也许我应该尝试扩展QThread. 但是在此之前,我想问一下,是否可以仅使用两个QTimer s timer1timer2并将它们的超时信号分别连接到线程,以实现伪"多线程程序?

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?

推荐答案

您可以将QTimer的timeout()信号连接到相应的插槽,然后调用start().从那时起,计时器将以固定的时间间隔发出timeout()信号.但是这两个计时器分别在主线程和主事件循环中运行.因此,您不能将其称为多线程.因为两个插槽不能同时运行.它们一个接一个地运行,如果一个阻塞主线程,则另一个将永远不会被调用.

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.

您可以拥有一个真正的多线程应用程序,方法是为应同时完成的不同任务提供一些类,并使用QObject::moveToThread更改对象的线程亲和力:

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();

请注意,Task1Task2继承自QObject.

这篇关于我可以使用QTimer来实现多线程算法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆