Search code examples
qtsignals-slotsqthread

Communication among threads in Qt


I'm working with threads in C++/Qt, each one to establish and mantain a QTcpSocket connection.

The problem is that when a disconnection from network comes, those threads must reconnect in a certain order. That's already working, but I have another problem: I need to know into each thread if only current thread has been disconnected, or all of them have been disconnected.

The first idea I had was to pass every thread a reference to a class where I would be able to store each thread status and check everyone else's.

But then I had an easier idea, and I would like to know if it would work or if it impossible: use Qt's slots and signals.

So, every thread I have comes from the same class, but passing different data to the Ctor. So the idea would be to create a slot and a signal inside that class, connect them and emit the signal passing an ID. Then, every thread's slot would be launched... or I may be completely wrong and the only slot launched would be the one from the very same thread which emited the signal.

Is this possible or not?


Solution

  • Signal and slot connections are done in run time, i.e. you are connecting specific instances of a class. You cannot emit a signal and "broadcast" it to every instance of your class. Signals between different threads is possible, but maintaining them could be a bit of a hassle (It's all explained pretty well in the documentation).

    If I were you, I'd probably look into QSemaphore or QSharedMemory.