队列T上的原子操作? [英] Atomic operation on queue<T>?
问题描述
我应该在带有队列的Visual C ++中实现一个类;在这个队列中,我必须执行原子操作.在网络上搜索时,我发现了类std :: atomic,但是我有一些疑问.第一个是:两者之间有什么区别?
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;
?
第二个问题是:我如何进行原子化操作,如push?
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?
任何建议,问候
推荐答案
A)atomic<queue <T>> fifo;
甚至都不会编译,因为std::atomic
需要一个可微写的类型
A) atomic<queue <T>> fifo;
will not even compile, because std::atomic
requires a trivially copyable type
B)将执行原子类型T的原子读或写,但是使用队列(推或弹出)的操作将不是原子的.
B) will perform atomic read or write of type T, but operations with queue (push or pop) will not be atomic.
您需要使用mutex
保护queue
操作:
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;
};
这篇关于队列T上的原子操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!