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?
Below given are the key differences between the C++ Vector and List: As the elements in the Vector are stored in the contiguous memory locations so they are synchronized whereas the elements in the List are stored randomly and connected with each other through the links (pointers) so they are non- synchronized.
The answer is no. Each array element has a region of memory reserved for it alone within the region attributed the overall array. Modifications of different elements therefore do not write to any of the same memory locations.
This has to be a dup. But, no, none of the standard containers are thread-safe.
C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.
vector
, like all STL containers, is not thread-safe. You have to explicitly manage the synchronization yourself. A std::mutex
or boost::mutex
could be use to synchronize access to the vector
.
Do not use a flag as this is not thread-safe:
isInUse
flag and it is false
isInUse
flag and it is false
isInUse
to true
isInUse
is false
and sets it true
vector
Note that each thread will have to lock the vector
for the entire time it needs to use it. This includes modifying the vector
and using the vector
's iterators as iterators can become invalidated if the element they refer to is erase()
or the vector
undergoes an internal reallocation. For example do not:
mtx.lock();
std::vector<std::string>::iterator i = the_vector.begin();
mtx.unlock();
// 'i' can become invalid if the `vector` is modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With