If I have a vector:
std::vector<std::atomic_bool> v(8);
and assuming I won't modify its size post creation, is it thread safe to call:
bool result = v[2].compare_exchange_strong(false, true);
* the values 8, 2, false and true are just given as an example use case.
CodePudding user response:
The OP appears to be asking whether multiple threads can evaluate
v[2].compare_exchange_strong(false, true)
when such evaluations are potentially concurrent, without causing a data race.
This will not compile because compare_exchange_strong
requires an lvalue as its first argument. I will assume that this issue is corrected.
The answer is yes. According to [container.requirements.dataraces]/1:
For purposes of avoiding data races (16.5.5.10), implementations shall consider the following functions to be
const
:begin
,end
,rbegin
,rend
,front
,back
,data
,find
,lower_bound
,upper_bound
,equal_range
,at
and, except in associative or unordered associative containers,operator[]
.
This implies that evaluating v[2]
is not allowed to modify the vector (nor any internal static data that might be shared between threads) and thus may not race with the same evaluation in another thread. The compare_exchange_strong
operation is being performed on an atomic object, so it's impossible for it to race with anything.