Atomic operation on queue<T>?

柔情痞子 提交于 2020-01-13 14:53:35

问题


I should implement a class in Visual C++ with a queue; in this queue I've to do atomic operation. Searching on the web, I found the class std::atomic , but I keep some questions. The first is: what's the difference among:

A) atomic <queue <T>> fifo;

B) queue <atomic <T>> fifo; ?

The second question is: how can I make atomic operation like push?

push (T.load) 

is the right solution?

The last question is: if I protect some operation on a queue with a mutex, still I have the need to do atomic operation on it?

Any advice is appreciated, Greetings


回答1:


A) atomic<queue <T>> fifo; will not even compile, because std::atomic requires a trivially copyable type

B) will perform atomic read or write of type T, but operations with queue (push or pop) will not be atomic.

You need to protect queue operations with mutex:

template<typename T>
class my_queue
{
public:
    void push( const T& value )
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_queque.push(value);
    }

    void pop()
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_queque.pop();
    }

private:
    std::queue<T> m_queque;
    mutable std::mutex m_mutex;
};


来源:https://stackoverflow.com/questions/32227321/atomic-operation-on-queuet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!