Thread mutex lock and return value
Hi,
I have this situation:
One thread class that needs to protect a QQueue but also needs to return dequeued value.
Code:
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,
Re: Thread mutex lock and return value
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:
Code:
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)
Re: Thread mutex lock and return value
Code:
m_qMutex.lock();
rc = m_qQueue.dequeue();
m_qMutex.unlock();
return rc;
Re: Thread mutex lock and return value
Hi,
Thanks,
pitonyak solution is good.
Re: Thread mutex lock and return value
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.
Re: Thread mutex lock and return value
Also possible:
Code:
return m_qQueue.dequeue();