1

Thread with an event loop

We have created a QTcpServer object in a separate thread and it is listening for incoming connections and processing them as they occur. At some point the is deleted and there is nothing to generate events in the thread.

Does the thread go into an endless block (using memory but no cpu) if not manually deleted?

Thread without an event loop

A QTcpServer object created and is listening.

Is the QTcpServer.listen() preventing the thread to just run through all the code and naturally finish?

What about the incoming connections? Do they have to be manually polled for?

László Papp
  • 51,870
  • 39
  • 111
  • 135
TheMeaningfulEngineer
  • 15,679
  • 27
  • 85
  • 143

1 Answers1

1

it is good practice to connect the finished signal of a thread to its own deleteLater slot so it can clean itself up, but this may cause dangling pointers if you keep a pointer to the QThread

QTcpServer.listen() will return immediately it just activates the port

when listening a TCPServer will emit a newConnection() signal each time a new connection is initiated by a client after which you can retrieve it with nextPendingConnection

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • And the second scenario, without the event loop? For example, I extend `QThread::run()` so that it doesn't call `exec()`. – TheMeaningfulEngineer Oct 22 '13 at 13:13
  • if there is no event loop then no events will be triggered on that thread, in the example the TCPServer will never emit a newConnection(), but you can wait for a connection with `waitForNewConnection()` – ratchet freak Oct 22 '13 at 13:16
  • But is it safe to consider that it will finish once all the code in it has been passed through. By finish I mean free the memory, and make me not have to worry about anything that happened on the threads inside (leaving dangling pointers etc.) – TheMeaningfulEngineer Oct 22 '13 at 13:27
  • if you connect the `finished` with the `deleteLater` slot then yes it will clean itself up – ratchet freak Oct 22 '13 at 13:40