Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ - vector of atomics fully thread safe?

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?

like image 757
dvs23 Avatar asked Aug 21 '17 09:08

dvs23


1 Answers

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.

like image 71
Bathsheba Avatar answered Oct 06 '22 01:10

Bathsheba