[ACCEPTED]-std::vector, thread-safety, multi-threading-multithreading

Accepted answer
Score: 28

Actually, it is absolutely pointless to state X is 16 or is not thread-safe! You need to qualify 15 for what kind of uses. For example, hardly 14 any class will be "thread-safe" when it 13 is somehow used in one thread and destroyed 12 in another.

That said, the statement that 11 std::vector<T> is not thread- safe, independent of how 10 often it is repeated, is wrong. However, it seems 9 most people neither understand nor appreciate 8 the thread-safety guarantees given. std::vector<T> is 7 thread-safe in the following sense:

  • You can read a vector object from multiple threads simultaneously.
  • If there is one thread changing a vector object, there shall be neither concurrent readers or writers.
  • Accesses to a vector object don't interfere with other vector objects.

This 6 applies to vector structure itself. Accesses 5 to contained object are bound to whatever 4 rules are imposed on them. These are apparently 3 not the thread-safety guarantees many people 2 have in mind but anything stronger won't 1 work with the container interface.

Score: 4

You call ptrVector->size() without locking it first. This 3 could easily be the cause of your problems. Make 2 sure to lock your vector before any reads 1 or writes.

Score: 0

Maybe you could use this instead?

concurrent_vector... from 1 the Intel Threading Building Blocks

https://software.intel.com/en-us/node/467758

Score: 0

To add to what has been said above by Dietmar 18 Kühl, when he states that thread safety

... applies 17 to vector structure itself. Accesses to 16 contained object are bound to whatever rules 15 are imposed on them.

it is indeed possible 14 to access the contiguous area of memory 13 allocated by a vector from multiple writing 12 threads, as long as each thread accesses 11 different elements of the vector. For example, to 10 populate an array of ten thousand elements 9 from ten threads, first set the size of 8 the vector to ten thousand, then pass a 7 pointer to the block of memory starting 6 at element 0, 1000, 2000, ... etc., to each 5 thread, which can happily write to its block 4 of a thousand elements. That will work correctly 3 as long as no thread calls any function 2 that could result in a reallocation of the 1 vector's storage.

More Related questions