tmlen
tmlen

Reputation: 9090

Efficiency of concurrent std::vector writes

According to http://en.cppreference.com/w/cpp/container#Thread_safety, it is safe to write to different elements of one std::vector, from different threads.

But if the value_type is smaller than the word size of the CPU (or the hardware destructive interference size), like (std::vector<char>), does this mean that access to elements is less efficient than it could be without the requirement for thread safety?

For example, does the read/write access imply memory fence/atomic instructions?

Upvotes: 2

Views: 1822

Answers (2)

SergeyA
SergeyA

Reputation: 62593

Yes it is safe, standard requires it to be safe. However, it might be inefficient due to what is called 'false sharing'.

False sharing happens when to individual threads update adjacent memory, which belongs to the same cache line. If those threads happen to be executed on two different cores, they end up invalidating the cache line on both CPUs and trigger expensive cache updates.

Code writer should make reasonable efforts to make the false sharing less likely by trying to assign close indexes to the same thread.

And to answer question I have just seen in the original post - no, there will be no compiler-generated fences on such writes.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477228

A conforming implementation of C++ must be able to write to a value of char without "inventing writes". In other words, char must be at least as big as the machine requires for isolated writes.

(It may still be inefficient to write to adjacent memory locations from multiple threads due to interference in the hierarchical memory, but it wouldn't be incorrect.)

Upvotes: 0

Related Questions