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

后端 未结 2 1019
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 03:07
array< atomic_size_t, 10 > A;

Neither atomic_init(A,{0}) nor A = {ATOMIC_VAR_INIT(0)} seem to work, returning an un

相关标签:
2条回答
  • 2021-01-18 03:25
    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}};
    };
    
    0 讨论(0)
  • 2021-01-18 03:44
    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

    0 讨论(0)
提交回复
热议问题