我试图找到答案一段时间,但我失败了.
让我们假设我们有一个shared_ptr从一个线程创建.然后我们将它传递shared_ptr给另外2个线程(例如使用一些队列).所以从这一刻开始,有两份原件shared_ptr,指向同一个原始指针.两个所有者线程都shared_ptr将从队列中获取它们的副本.然后他们会将它传递给另一个线程或将其销毁.
问题是 - 它安全吗?原始指针是否会被正确销毁(没有竞争引用计数器?)

可以有人解释一下,为什么作者认为下面部分源代码导致竞争?作者说:"如果有多个线程从队列中删除项目,但是在单一消费者系统中(如此处所讨论的),这种设计受制于空,前和弹出调用之间的竞争条件,这不是问题."
请参阅: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)