Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How to initialise an array of atomics?

array< atomic_size_t, 10 > A;

Neither atomic_init(A,{0}) nor A = {ATOMIC_VAR_INIT(0)} seem to work, returning an unintelligible error. How would you initialise an array of atomics to 0s?

Even for loops updating one element of the array at every step does not work. What is the purpose of arrays of atomics if we can't initialise them?

I would also like to add that the actual size of my array is huge (not 10 like in the example), so I would need a direct initialisation.

like image 489
Pippo Avatar asked Oct 17 '13 18:10

Pippo


1 Answers

std::array<std::atomic<std::size_t>, 100> A;
for(auto&x:A)
  std::atomic_init(&x,std::size_t(0));

does the job using

clang++ -std=c++11 -stdlib=libc++ -Weverything -Wno-c++98-compat

using clang-3.3. I also tried with gcc 4.8, but it doesn't support std::atomic_init(). However, I suppose you can replace std::atomic_init(&x,std::size_t(0)) with x=std::size_t(0).

Note that std::atomic<> is not copyable, which breaks some container methods (including construction of std::array<std::atomic<T>> from a T). Also, storing atomics in an array may cause false sharing, affecting performance.

EDIT 2019

The code in the accepted answer by Zac Howland does not compile (neither with clang nor with gcc). Here is a version that will

struct foo
{
    std::array<std::atomic_size_t,2> arr= {{{0},{0}}};
    std::atomic_size_t arr_alt[2] = {{0},{0}};
};
like image 125
Walter Avatar answered Nov 04 '22 05:11

Walter