Thread Safe Compile Time Array

79 Views Asked by At

I need to operate on a std::array by accessing/changing the array at given index as well as iterating over the elements of the array.

Assuming the array elements are shared_ptr to thread safe objects. Is there any concerns on the thread safety when operating on the array from different threads?

Context: How to make the below thread safe,

#include <array>
#include <memory>

struct SafeQueue
{
    void push(const double d) {};
    bool try_pop(double& d) {};
};

struct Broadcaster
{
    std::array<std::shared_ptr<SafeQueue>, 10> m_queues;
    void broadcast(const double d)
    {
        for(auto p : m_queues)
            if(p) p->push(d);
    }

    bool addQueue(const std::shared_ptr<SafeQueue>& q)
    {
        for(auto& p : m_queues)
            if(!p) 
            {
                p = q;
                return true;
            }
        return false;
    }
};

Assume we are calling broadcast and addQueue from different threads.

I think I can solve this with atomic index but was thinking if there is any better.

0

There are 0 best solutions below