In my program I've some threads running. Each thread gets a pointer to some object (in my program - vector). And each thread modifies the vector.
And sometimes my program fails with a segm-fault. I thought it occurred because thread A begins doing something with the vector while thread B hasn't finished operating with it? Can it bee true?
How am I supposed to fix it? Thread synchronization? Or maybe make a flag VectorIsInUse
and set this flag to true while operating with it?
vector
, like all STL containers, is not thread-safe. You have to explicitly manage the synchronization yourself. Astd::mutex
orboost::mutex
could be use to synchronize access to thevector
.Do not use a flag as this is not thread-safe:
isInUse
flag and it isfalse
isInUse
flag and it isfalse
isInUse
totrue
isInUse
isfalse
and sets ittrue
vector
Note that each thread will have to lock the
vector
for the entire time it needs to use it. This includes modifying thevector
and using thevector
's iterators as iterators can become invalidated if the element they refer to iserase()
or thevector
undergoes an internal reallocation. For example do not:That's why pretty much every class library that offers threads also has synchronization primitives such as mutexes/locks. You need to setup one of these, and aquire/release the lock around every operation on the shared item (read AND write operations, since you need to prevent reads from occuring during a write too, not just preventing multiple writes happening concurrently).
If you want a container that is safe to use from many threads, you need to use a container that is explicitly designed for the purpose. The interface of the Standard containers is not designed for concurrent mutation or any kind of concurrency, and you cannot just throw a lock at the problem.
You need something like TBB or PPL which has
concurrent_vector
in it.