I have a std::vector<std::atomic<size_t>>
vec. Is it safe to run vec[index].fetch_add(1, std::memory_order_release)
or store/load with multiple concurrent threads on it? I think it should be, because reading is thread safe and writing to one entry at the same time from multiple threads is impossible because of the atomics - is that right?
No it is not, in general, thread safe since the container itself is not atomic.
That said, so long as you don't change what is in the vector (i.e. doing anything that invalidates the return of data()
) , you'll be fine.
Sadly you can't resort to std::atomic<std::vector<...>>
as a std::vector
is not trivially copyable.
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