5

I have two QObjects A and B living in separate QThreads. A will emit a signal while B has a matching slot. I want to use connect() to connect A's signal to B's slot.

So the question is, is the connect() call thread safe? Does it matter in which of the two threads the connect is made?

Mr. Developerdude
  • 9,118
  • 10
  • 57
  • 95

1 Answers1

4

Yes, QObject::connect() is thread safe method:

Note: All functions in this class are reentrant, but connect(), connect(), disconnect(), and disconnect() are also thread-safe.

It doesn't matter from which thread you do the connection. But you should care about using of auto connection(default connection), unique connection or queued connection between your objects. And you should run event loops in both of your threads.

Also I strongly suggest you to check following articles: first, second.

Max Go
  • 2,092
  • 1
  • 16
  • 26
  • 1
    Using Qt::QueuedConnection or not really depends on what behavior you want. Running an event loop in each thread is not necessary at all, again it depends on what you want. – Martin Sep 26 '14 at 22:45
  • @Martin, queued connection tells Qt, that signal will be processed delayed in the event loop of the slot's thread. That's why it's needed to run event loops in both threads to communicate between objects successful. If you don't do this, then your code is not thread safe and prepare to get random crashes in GUI thread event loops... also if the objects belong to the thread without event loop, the emitted signal will be never processed and delivered to slot. Any objections? maybe something changed in Qt 5 – Max Go Sep 27 '14 at 07:14
  • I only read Qt5 doc so can't say about Qt<5 but, I maintain what I said, Qt::QueuedConnection is not mandatory. An event loop in a thread is also not mandatory too. Qt doc says: "If no event loop is running, events won't be delivered to the object.", so I agree with you about this but, it also says: "You can manually post events to any object in any thread at any time using the thread-safe function QCoreApplication::postEvent()". Hard to convince you in 500 characters but read Qt doc carefully and understand the code you write is the only thing that matters. – Martin Sep 27 '14 at 16:10
  • In Qt5 AutoConnection is default. This type of connection will be queued only when objects are on different threads. I usually use Qt::UniqueConnection because it is the same as AutoConnection, only prevents the same connection being made more than once (by mistake or otherwize). – Mr. Developerdude Sep 27 '14 at 21:14
  • Thanks, I have updated the answer. Regarding QCoreApplication::postEvent, it looks like using this method is not possible to post the signal from object in one thread to the slot of object in another thread. It exists method QApplication::processEvents(), but actually I don't think that it will work too. Will try myself to figure out :) – Max Go Sep 28 '14 at 10:02