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 be 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::mutexorboost::mutexcould be use to synchronize access to thevector.Do not use a flag as this is not thread-safe:
isInUseflag and it isfalseisInUseflag and it isfalseisInUsetotrueisInUseisfalseand sets ittruevectorNote that each thread will have to lock the
vectorfor the entire time it needs to use it. This includes modifying thevectorand using thevector‘s iterators as iterators can become invalidated if the element they refer to iserase()or thevectorundergoes an internal reallocation. For example do not: