Search code examples
c++arraysc++11atomicstdatomic

How do I initialize an array of std::atomics to zeros?


std::array< std::atomic_size_t, 10 > A;
// ...
std::atomic_init(A, {0}); // error
A = {ATOMIC_VAR_INIT(0)}; // error

How would you initialize an array of std::atomic 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 initialize 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-initialization.


Solution

  • std::array<atomic_size_t, 10> arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

    or if you can compile for C++11

    std::array<std::atomic_size_t, 10> arr{{{0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0} }}; // double braces required
    

    Example: https://www.ideone.com/Mj9kfE

    Edit:

    It just occurred to me that you are trying to store atomics, which are not copyable, into a collection that would require they be copyable (Note: I can't get to my copy of the standard at the moment. I know this holds true for the other collections, but I'm unsure if it holds true for std::array as well).

    A similar problem was posted a while back: Thread-safe lock-free array