Thread-safe usage of QList<QString> ?
-
Hi,
Is this code thread-safe? "remaining" is a QList<QString>:
@QString target = remaining.first();
remaining.pop_front();@
If not, how should I work it out?
So far I tried mutex to lock it, but after the first thread unlock the mutex, the rest of threads just wait forever: (the mutex is a private variable in the class)
@mutex.lock(); // locked forever even unlock() processed
QString target = remaining.first();
remaining.pop_front();mutex.unlock();
qDebug() << "Unlocked"; // I saw this message@ -
Is the "mutex" object is the same for all threads? Only 1 instance?
-
It's a private variable inside the class, only one instance, question updated.
[quote author="TioRoy" date="1350530383"]Is the "mutex" object is the same for all threads? Only 1 instance?[/quote]
-
One thread can call lock() multiple times?
You can try to create the QMutex in a recursive mode ("link":http://qt-project.org/doc/qt-4.8/qmutex.html#QMutex)
-
You could also try to use "QReadWriteLock":http://qt-project.org/doc/qt-4.8/qreadwritelock.html or "QMutexLocker":http://qt-project.org/doc/qt-4.8/qmutexlocker.html, they are easier to work with and abolutely sufficient for your use case.