Exchanging QObject based classes with QThreads via signals
I read a book about QThreads and I alos read the html documentations about that topic. There is one thing that I obviously do not understand:
I read that QObject based classes cannot be shared across threads. But how can a Threads generate data in a QObject based class and return the result or notify about the current status?
I saw some examples, where QThreads send signals using QObject base classes as arguments. Is that wrong? If not, what conditions must be cared when doing that?
Hmm, I can't remeber where I saw such an example. So I tried to find some with google but all examples that I found use only simple types or QStrings or one of the collection classes.
It seems that that I understood the rule correctly and simply had a wrong example in my mind.
To be sure: Is it correct, that passing QObjects via signals and slots to other threads is forbidden?
I don't think there is anything wrong with sending QObjects between threads. Of course you have to be careful with locking as with any shared resource, and of top of that you have to deal with QObject thread affinitiy.
So, the object you're trying to hand over from a secondary thread to, say, the GUI thread, must not have a parent, and if it participates in any kind of event handling, you have to do:
from the thread that created the QObject. I think we need a concrete example of what you're trying to do though.
I have no concrete ecample at the moment. But when I fee the need to pass a QObject as signal/slot argument, I will come back and post it here.
I have an example now.
I am currently writing a HTTP web server - just to learn it. It executes a QTcpServer in the main thread and processes incoming requests in 10 worker threads.
When a new connection comes in, I get the connection via QTcpServer::nextPendingConnection() which returns a QTcpSocket which is derived from QObject. Now after getting that QTcpSocket in the main thread, I need to pass it to one of the 10 worker threads. The easiest way would be to send them as a signal, but this does not work, als the documentation of QTcpServer specially highlights.
The documentation of QTcpServer also provides a solution: Passing the integer socket descriptor ID instead of a QSocket object. SO in this case, it was easy to workaround the limitation.