2

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

4

1 回答 1

3

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

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

 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.

于 2014-06-23T03:38:47.677 回答