I am working on a C++ port of a Java library. One of the problems is I am not able to find equivalent of Java's AtomicLongArray. Anyone knows if there is anything already equivalent in c++ 11 or how to implement similar functionality? I had a look at C++11 atomics but could not find anything.
问题:
回答1:
The docs for AtomicLongArray say:
A long array in which elements may be updated atomically. See the
java.util.concurrent.atomic
package specification for description of the properties of atomic variables.
That sounds to me like a simple array of std::atomic<long>
:
std::array<std::atomic<long>, N> array;
// or, if size is not known at compile time
std::vector<std::atomic<long>> vector(n);
Note that only the elements are atomic, the container itself isn't, so don't go around push_back
ing into the vector.
回答2:
In [container.requirements.dataraces] the standard says
-2- Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting
vector<bool>
, are modified concurrently.-3- [ Note: For a
vector<int> x
with a size greater than one,x[1] = 5
and*x.begin() = 10
can be executed concurrently without a data race, butx[0] = 5
and*x.begin() = 10
executed concurrently may result in a data race. As an exception to the general rule, for avector<bool> y, y[0] = true
may race withy[1] = true
. —end note ]
So any container (except evil vector<bool>
) allows separate elements to be updated without data races. To also ensure updates to a single element are safe, use a container of atomic types, e.g. std::vector<std::atomic<long>>