I have two QMutex objects and I need to lock them both, erase()
method. But the sequence is not important.
So, now I am waiting while one QMutex is in unlocked (QMutexLocker locker(&listMutex)
) state and than I wait for another (QMutexLocker locker(&writeMutex)
).
But it would be more efficiently to wait for a mutex which is unlocked the first. And than wait for the other one. Than waiting time will be shorter.
How could be implemented such behaviour?
Should I create additional recursive QMutex or QSemaphore and synchronize states of both QMutex with this new object and than wait not for my QMutex but for this new object.
That should work, but maybe there is an easier way without duplicating QMutex objects?
class MyQThread:
public: QThread
{
...
QList<QString> list;
QString string;
QMutex listMutex;
QMutex writeMutex;
}
void MyQThread::erase()
{
QMutexLocker locker(&listMutex);
list.clear();
QMutexLocker locker(&writeMutex);
string.clear();
}
void MyQThread::run()
{
forever
{
listMutex.lock();
string = list.takeFirst();
listMutex.unlock();
writeMutex.lock();
if(!string.isEmpty())
...//do something
writeMutex.unlock();
}
}
ah, ok...
Its a bit of a fiddle, but you can use "tryLock()", somthing like this:
Note: tryLock will return true if it acutally locked the mutex, or false if it did not.
---- EDIT Example 2: ----