问题
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