Shf
Shf

Reputation: 3493

QTimer timeout and QMutex interaction

Let's say we have some basic timer and a slot which is invoked periodically.

SomeObject::SomeObject()
{
  QTimer *timer = new QTimer;
  connect(timer , SIGNAL(timeout()), this, SLOT(updateState()));
}

void  SomeObject::updateState()
{
   // some operations leading to update of updatedValue
}

I also have function from same object which forces updates and returns some value.

bool  SomeObject::getLatestState()
{
  updateState();
  return updatedValue;
}

This function may be directly called from different threads. This brings question of thread safety to mind. Simple mutex lock in getLatestState will not help as in some rare cases getLatestState is called from another thread that starts updateState. And at the same time timer's timeout may occur. Can you help me handle this situation properly?

Upvotes: 0

Views: 1202

Answers (1)

Vahagn Avagyan
Vahagn Avagyan

Reputation: 776

QMutexLocker can be used in such situations

this my exampl

static QMutex mainMutex;
.....
MainController* MainController::s_instance = NULL;
.....    
MainController* MainController::getInstance()
{
    if(!s_instance){
        QMutexLocker lock(&mainMutex);
        if(!s_instance){
            s_instance = new MainController;
        }
    }
    return s_instance;
}

getInstance() function directly called from different threads.

Upvotes: 1

Related Questions