2013-07-20 48 views
1


我想问一个关于应用程序体系结构的问题
1.将有用于提供用户交互的主要GUI线程
2.基于UDP套接字的接收线程将接收UDP数据包当他们到达(希望这会阻止
3.另一个线程发送基于事件的,以及周期性的UDP数据包

如何实现在Qt的这种架构,基本上我有以下问题:。
1.对于接收线程,我该如何阻止它?
我知道readyRead()信号,并且我可以将它连接到某个处理数据报的插槽,但是如何循环这个以便这个线程永远这样做。

2.发送线程,我可以生成一个信号形成将被发送线程接收和这里插槽将写在插座上的一些数据,但再怎么将这个线程生存,当没有东西发送GUI线程,我的意思是循环,轮询什么东西?Qt阻塞线程和跨线程通信

回答

1

在辅助线程中使用事件循环。

QThread::exec()启动线程的事件循环,该循环将一直运行,直到调用QThread::quit()。这应该解决你的“如何等待,直到发生问题”的问题。 QThread::run()的默认实现只是调用exec(),所以我愿意这样做。您可以在main()方法中设置所有内容,例如发件人线程:

//Create UI 
MainWindow mainWindow; 
mainWindow.show(); 

//set up sender thread and the QObject doing the actual work (Sender) 
QThread senderThread; 
Sender sender; //the object doing the actual sending 
sender.moveToThread(&sender); //move sender to its thread 
senderThread.start(); //starts the thread which will then enter the event loop 

//connect UI to sender thread 
QObject::connect(&mainWindow, SIGNAL(sendMessage(QString)), &sender, SLOT(sendMessage(QString)), Qt::QueuedConnection); 

... 

const int ret = app.exec(); // enter main event loop 

senderThread.quit(); //tell sender thread to quit its event loop 
senderThread.wait(); //wait until senderThread is done 

return ret; // leave main 

发件人也只是用的sendMessage()槽做的发送,一个QTimer加上周期性UDP封装另一个插槽等一个QObject