How to declare a vector of atomic in C++

后端 未结 4 1872
暗喜
暗喜 2020-11-27 16:01

I am intending to declare a vector of atomic variables to be used as counters in a multithreaded programme. Here is what I tried:

#include 
#in         


        
4条回答
  •  伪装坚强ぢ
    2020-11-27 16:55

    As others have properly noted, the cause of the compiler's error is that std::atomic explicitly prohibits the copy constructor.

    I had a use case where I wanted the convenience of an STL map (specifically I was using a map of maps in order to achieve a sparse 2-dimensional matrix of atomics so I can do something like int val = my_map[10][5]). In my case there would be only one instance of this map in the program, so it wouldn't be copied, and even better I can initialize the entire thing using braced initialization. So it was very unfortunate that while my code would never attempt copying individual elements or the map itself, I was prevented from using an STL container.

    The workaround I ultimately went with is to store the std::atomic inside a std::shared_ptr. This has pros, but possibly a con:

    Pros:

    • Can store std::atomic inside any STL container
    • Does not require/restrict using only certain methods of STL containers.

    Pro or Con (this aspect's desirability depends on the programs' use cases): - There is only a single shared atomic for a given element. So copying the shared_ptr or the STL container will still yield a single shared atomic for the element. In other words, if you copy the STL container and modify one of the atomic elements, the other container's corresponding atomic element will also reflect the new value.

    In my case the Pro/Con characteristic was moot due to my use case.

    Here's a brief syntax to initialize a std::vector with this method:

    #include 
    #include 
    #include 
    
    std::vector > > vecAtomicInts
    {
        std::shared_ptr >(new std::atomic(1) ),
        std::shared_ptr >(new std::atomic(2) ),
    };
    
    // push_back, emplace, etc all supported
    vecAtomicInts.push_back(std::shared_ptr >(new std::atomic(3) ) );
    
    // operate atomically on element
    vecAtomicInts[1]->exchange(4);
    
    // access random element
    int i = *(vecAtomicInts[1]);
    

提交回复
热议问题