March 18, 2011

usamytch usamytch
Lab Rat
37 posts

Locking of semi-read-only QVector

 

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?

4 replies

March 18, 2011

Gerolf Gerolf
Area 51 Engineer
3210 posts

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.

 Signature 

Nokia Certified Qt Specialist.
Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

March 18, 2011

ZapB ZapB
Robot Herder
1354 posts

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) ;-).

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

March 18, 2011

usamytch usamytch
Lab Rat
37 posts

Thank you for the answers!

March 18, 2011

ZapB ZapB
Robot Herder
1354 posts

No problem. Sounds like you could be a potential user of this class [qt.gitorious.org] that I wrote. I have a small wrapper around this class that makes it into a thread-safe container for the producer-consumer pattern.

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

 
  ‹‹ [Solved]problem using Qftp      QScrollArea issues ››

You must log in to post a reply. Not a member yet? Register here!