c++ 11 equivalent of java atomiclongarray

2019-08-14 17:32发布

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.

2条回答
Fickle 薄情
2楼-- · 2019-08-14 18:10

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, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector<bool> y, y[0] = true may race with y[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>>

查看更多
Animai°情兽
3楼-- · 2019-08-14 18:28

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_backing into the vector.

查看更多
登录 后发表回答