Locking of semi-read-only QVector
-
wrote on 18 Mar 2011, 11:23 last edited by
Good day, colleagues!
Suppose I have 2 threads and QVector<double> with fixed size, initialized as QVector<double> (fixed_size). First thread consequently fills this QVector with data. Second thread only reads this QVector and it's guaranteed that second thread reads only elements, which are already processed by the first thread. For example, if second thread reads vector.at(0), it's guaranteed that vector.at(0) is filled by the first thread and will not change anymore.
The question is shoud I lock QVector with QMutex or not?
-
wrote on 18 Mar 2011, 11:32 last edited by
if you don't change the size anymore, it should be save.
But it's saver to lock ;-)
If it's guaranteed that the vector will never be resized, it should work.
-
wrote on 18 Mar 2011, 13:16 last edited by
As Gerolf said as long as you do not resize the vector (or call other methods that can change the memory layout such as reserve()) and you are sure that you are only reading from indexes that are not being written to at the same time (e.g. by using semaphores) it should be safe (I think) ;-).
-
wrote on 18 Mar 2011, 13:23 last edited by
Thank you for the answers!
-
wrote on 18 Mar 2011, 13:27 last edited by
No problem. Sounds like you could be a potential user of "this class":http://qt.gitorious.org/qt/qt/merge_requests/2364 that I wrote. I have a small wrapper around this class that makes it into a thread-safe container for the producer-consumer pattern.
3/5