use*_*475 1 c++ multithreading synchronization
可以有人解释一下,为什么作者认为下面部分源代码导致竞争?作者说:"如果有多个线程从队列中删除项目,但是在单一消费者系统中(如此处所讨论的),这种设计受制于空,前和弹出调用之间的竞争条件,这不是问题."
请参阅:http://digg.com/newsbar/topnews/How_to_write_a_Thread_Safe_Queue_in_C
谢谢
template<typename Data>
class concurrent_queue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
public:
void push(const Data& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
Data& front()
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.front();
}
Data const& front() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.front();
}
void pop()
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.pop();
}
};
Run Code Online (Sandbox Code Playgroud)
inf*_*inf 10
如果你打电话给empty你,检查弹出一个元素是否安全.在线程系统中可能发生的情况是,在您检查到该队列不为空之后,另一个线程可能已经弹出了最后一个元素,并且队列不为空也不再安全.
thread A: thread B:
if(!queue.empty());
if(!queue.empty());
queue.pop();
->it is no longer sure that the queue
isn't empty
Run Code Online (Sandbox Code Playgroud)