Qt阻塞线程和跨线程通信

时间:2013-07-20 10:21:03

标签: multithreading qt qthread


我想问一个关于应用程序架构的问题。将有用于提供用户交互的主GUI线程2。一个基于UDP套接字的接收线程,它将在到达时接收UDP数据包(希望它被阻塞。)3。另一个用于发送基于事件和周期性UDP数据包的线程。

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

2.在发送线程中我可以从GUI线程生成一个信号,该信号将由在这里发送线程和一个插槽将在套接字上写入一些数据,但是当它没有任何内容发送时,这个线程将如何生存下去,我的意思是循环,对什么进行轮询?

1 个答案:

答案 0 :(得分: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

发件人只是一个QObject,其sendMessage()插槽用于发送,QTimer加上另一个用于定期UDP包的插槽等。

相关问题