Search code examples
c++multithreadingqt

Two different slots calling same method - Thread safety


I'm relatively new to programming, and Qt in particular. I'm writing an application that counts minutes and seconds using two different threads(secThread and minThread). Both threads send a signal to the gui when the minutes/seconds should be incremented.

The signals and slots are connected in the gui class like this:

connect(secThread, SIGNAL(increment()), this, SLOT(incrementSeconds()));
connect(minThread, SIGNAL(increment()), this, SLOT(incrementMinutes()));

And the slots are implemented like this:

void ClockGUI::incrementMinutes(){
  minutes++;
  if(minutes==60) minutes=0;
  updateDisplay();
}


void ClockGUI::incrementSeconds(){
  seconds++;
  if(seconds==60) seconds=0;
  updateDisplay();
}

As you can see, both slots call the private updateDisplay() method:

void ClockGUI::updateDisplay(){
  lblMinutes->display(minutes);
  lblSeconds->display(seconds);
}

As far as I understand, calling the same slot from different threads is thread-safe, but my question is this: Is it thread-safe to call the same method from within two different slots?


Solution

  • You are using the default Qt::AutoConnection as per documentation when connecting your signals to the slots of the receiver (this, ClockGUI*).

    QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const char * method, Qt::ConnectionType type = Qt::AutoConnection) const

    See the definition of it in the documentation:

    Qt::AutoConnection 0 (Default) If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted.

    Qt::DirectConnection 1 The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread.

    Qt::QueuedConnection 2 The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.

    That means, your receiver thread will execute these slots functions as per Qt::QueuedConnection, in the (chronological) order of emission in your threads, but the order probably does not matter much in your case. That is, whichever of your threads gets to the signal emission earlier.

    The Qt event loop is basically based on FIFO (first-in-first-out) in this regard.

    Other than that, I am not sure what you mean by thread-safe in here.