我想问一个关于应用程序架构的问题
将有用于提供用户交互的主GUI线程基于UDP套接字的接收线程,它将在UDP包到达时接收
我如何在Qt中实现这个架构,基本上我有以下问题:
我知道readyRead()信号,我可以将它连接到某个处理数据报的插槽上,但是我该如何循环它,使这个线程永远这样做呢?
发布于 2013-07-20 13:37:10
在辅助线程中使用事件循环。
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()
插槽的QObject
,一个QTimer
加上用于周期性UDP包的另一个插槽,等等。
https://stackoverflow.com/questions/17761198
复制相似问题