PDA

View Full Version : can i use stl type vector as the shared memory of two threads?



calmspeaker
29th December 2008, 02:56
I try it , at least now it works well.
The program will be running almost all day, the size of vector could be large,
Can I use vector as the shared memory of two threads? I use QThread.!

ps: one thread is producer, the other is consumer.The producer emit signal when the shared vector has some data, the consumer consume the data and call clear() of the vector.

Thank you in advance

caduel
29th December 2008, 08:58
You can use anything as long as you synchronize the access.
A std::vector is not thread-safe (nor are QList, QMap, ...), so you have to use a QMutex or something like that to synchronize access. (Note: you might use a QList or whatever just as well.)

HTH

calmspeaker
29th December 2008, 15:01
er, another question:
is vector or qvector as efficient as circular buffer in the producer/consumer example in qt doc ?

caduel
29th December 2008, 18:24
depends on how you use it: the vector itself is about as efficient as it can get (as long as you do not add/remove elements (pop_front()).
The important thing for efficiency might be locking: do you lock the whole vector or just the critical parts of it? If you lock the whole vector then you restrict concurrency more than perhaps necessary.

The most efficient thing is to use a static array and implement a circular buffer on it. On the other hand, the tiny loss in speed when using higher level structures might be negligible when writing an app that is not speed critical but where reliability and understandability of the code are more important.

HTH

chaoticbob
29th December 2008, 19:50
You might also want to take a look at boost's circular buffer. I haven't done anything practical with it - but it may be worth consideration.