Consider the following code in a multithread program:
QString target = remaining.first(); // remaining is a QVector<QString> class
remaining.pop_front();
Would it be safe? Looks like multiple thread may use the same “target” simultaneously. Or what’s the safe way to retrieve + erase the first value?
Without a mutex protecting that code, no, it’s not at all safe.
I don’t know
QVectorin detail but I believe it’s OK for two threads to both do:This simply copies an element of the vector, so each thread has its own
QStringobject calledtargetand they are independent objects (behind the scenes they use implicit sharing so are not independent, but you should be able to treat them as independent)But this line modifies the
QVector:This means two threads modify the same object without any synchronisation. If the first thread is still accessing the vector by calling
remaining.first()when the second thread callspop_front()then there is a data race, with undefined behaviour.Similarly, if both threads call
pop_front()concurrently they will both try to remove the first element, what happens there is completely unpredictable. You might erase one element, or two, or none, or crash the entire program immediately. As another possibility, consider what happens if the vector only has one element. Both threads check it’s not empty, copy thefirst()element, then callpop_front(), which tries to remove two elements when there’s only one. You’re program is broken.The safe way to do it is protect the code with a mutex, where
mutexis some global or otherwise shared variable that is visible to both threads: