PDA

View Full Version : Thread mutex lock and return value



^NyAw^
12th February 2010, 15:16
Hi,

I have this situation:
One thread class that needs to protect a QQueue but also needs to return dequeued value.



bool myThread::getResult()
{
m_qMutex.lock();
return m_qQueue.dequeue();
m_qMutex.unlock(); //This will never be executed because of return statment, and will cause a deadlock
}


So, how can I do this in a correct way. One solution is to get the mutex of the thread from the caller object and lock and unlock there but I want to know if there is a more elegant solution.

Thanks,

high_flyer
12th February 2010, 15:43
In general it is a VERY bad and dangerous practice to lock mutex and call other methods/functions, since you never know if another mutex will be locke there too.
You should only lock local data.

Like so:


reentrantFunction()
{
//good
m_muext.lock()
m_data = some_data;
m_mutex.unlock()

//bad
m_mutex.lock();
someFunc();
m_mutex.unlock()
}


In the case you posted, m_qQueue.dequeue(); has to be re-entrant it self, which means there should the mutex be locked and released and not in getResult(). ( as you can see, another good reason not to lock mutex before function calls)

pitonyak
12th February 2010, 16:04
m_qMutex.lock();
rc = m_qQueue.dequeue();
m_qMutex.unlock();
return rc;

^NyAw^
12th February 2010, 16:14
Hi,

Thanks,

pitonyak solution is good.

high_flyer
12th February 2010, 16:21
indeed, I over looked the fact you are using a "standard" class, basically as a type - sorry for that.
But be careful in any other cases with locking mutexes before function calls.

franz
13th February 2010, 07:32
Also possible:


QMutexLocker locker(&m_qMutex);
return m_qQueue.dequeue();