2

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.

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
polapts
  • 5,493
  • 10
  • 37
  • 49
  • 6
    You'd greatly increase your potentially helpful audience if you explained what atomiclongarray is. That way you'd get help from people that knows C++, but not Java. – R. Martinho Fernandes Jun 13 '12 at 16:53

2 Answers2

9

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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
0

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>>

Community
  • 1
  • 1
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • Last time I checked you can't have vectors of atomic types since they don't have copy constructors. See http://stackoverflow.com/questions/12003024/error-with-copy-constructor-assignment-operator-for-a-class-which-has-stdatomi – Sean McCauliff Mar 13 '14 at 01:28
  • 1
    @SeanMcCauliff, that's not true, you can declare e.g. `std::vector> v(10);` you just can't copy it or insert more elements into it. – Jonathan Wakely Mar 13 '14 at 08:47
  • //The following program produces over 500 lines of error messages when compling with gcc 4.7.2. Is this an unimplemented feature in gcc? #include #include using namespace std; int main(int argc, char** argv) { vector> atomicVector(10); return 0; } – Sean McCauliff Mar 14 '14 at 17:31
  • Never mind I forgot to add -std=c++11. So you can't assign to a vector of atomic longs nor can you initialize them. Go it. – Sean McCauliff Mar 14 '14 at 17:44