I want to ask a question about Application architecture
1. There will be the main GUI thread for providing user interaction
2. A Receive thread based on UDP socket that will receive UDP packets as they arrive (want this to be blocking.
3. Another thread for sending event based as well as periodic UDP packets.
How do I implement this architecture in Qt, basically i have following questions:
1. For the Receive Thread, how do I make it blocking ?
I know about readyRead() signal, and I can connect it to some slot that will process the datagram, but how do i loop this so that this thread does this forever.
2. In send Thread I can generate a signal form the GUI thread which will be received by the Sending Thread and a slot here will write some data on the socket, but again how will this thread survive when it has nothing to send, I mean loop, poll over something what ?
1
votes
1 Answers
1
votes
Use event loops in the secondary threads.
QThread::exec()
starts the thread's event loop which will run until QThread::quit()
is called. That should solve your "how to wait until something happens" problem. The default implementation of QThread::run()
just calls exec()
, so I'd go with that. You could set everything up in your main()
method, e.g. for the sender thread:
//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
Sender would just be a QObject
with a sendMessage()
slot doing the sending, a QTimer
plus another slot for the periodic UDP packages, etc.