Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt QTimer is it safe to stop it this way?

Tags:

c++

timer

qt

Is it safe to stop Qt's timer in it's "timeout" signal/slot function? Can't seem to find any information in Qt documentation about the QTimer.

I have created a timer that is periodically sending a "keep alive" messages to the server. I want this timer to be stopped if there is some kind of error while sending my message.

private:
   QTimer* mpKeepAliveTimer;

Timer is initialized like this:

mpKeepAliveTimer = new QTimer(/* this */);

QObject::connect(mpKeepAliveTimer, SIGNAL(timeout()), this, SLOT(OnKeepAlive()));

mpKeepAliveTimer->start(KEEP_ALIVE_PERIOD);

Stopped like this:

if (mpKeepAliveTimer != NULL) // <-- Edited
{
    if (mpKeepAliveTimer->isActive() == true)
        mpKeepAliveTimer->stop();

    delete mpKeepAliveTimer;
    mpKeepAliveTimer = NULL;
}

Timeout function looks like this:

void Classname::OnKeepAlive()
{
   if (isErrorFound == true)
      mpKeepAliveTimer->stop();   // <---- IS THIS SAFE?
}

Thanks.

like image 655
Gediminas Avatar asked Aug 16 '12 07:08

Gediminas


1 Answers

As long as you are not explicitly using Queued Connections, this is safe.
This is because the emit timeout() function will not return until all the slots it's connected to were processed.

If you were however using Queued Connections, it could in theory happen that there are still unprocessed timeout events in the Event Queue, so to make it hyper-safe you could use the following:

void Classname::OnKeepAlive()
{
    if (!mpKeepAliveTimer || !mpKeepAliveTimer->isActive()) return;

    if (isErrorFound)
    {
        mpKeepAliveTimer->stop();
    }
}

Note that the condition in your stop function should be != NULL instead of == NULL. You can also write that function as follows, however:

if (mpKeepAliveTimer)
{
    delete mpKeepAliveTimer;
    mpKeepAliveTimer = NULL;
}

As already suggested in the comments, QTimer will stop itself in its destructor.

like image 83
Tim Meyer Avatar answered Nov 03 '22 19:11

Tim Meyer