getter 方法中的常量引用
您能检查一下这段代码吗?我相信这里没有什么问题。
你可能特别是。喜欢查看使用模板的类的出队函数。
void enqueue(const T &data)
{
_mutex.lock();
_queue.push(data);
_mutex.unlock();
}
T const& dequeue()
{
_mutex.lock();
T &data = _queue.back();
_queue.pop();
_mutex.unlock();
return data;
}
Can you please review this code. I believe there is nothing wrong here.
You may esp. like to look the dequeue function of a class where template is used.
void enqueue(const T &data)
{
_mutex.lock();
_queue.push(data);
_mutex.unlock();
}
T const& dequeue()
{
_mutex.lock();
T &data = _queue.back();
_queue.pop();
_mutex.unlock();
return data;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
出队
中,您返回一个悬空引用。一旦您弹出
物体,它就不复存在了。
In
dequeue
, you return a dangling reference. Once you'vepop
ped theobject, it ceases to exist.
只是没有。
首先,你不能只是在其上添加一个互斥体并称其为线程安全的。这不仅会在不必要的情况下产生可怕的开销,而且还会破坏某些操作的原子性 - 例如,您无法保证如果我检查队列的大小,然后它是否大于零,从队列中取出一个 - 因为有人可能同时清空了它。或者,如果我取下一个物体,但现在它已被弹出怎么办?哎呀。
线程安全在于不同时访问数据,而不仅仅是在数据结构中插入互斥体并调用它完成。
其次,如果您要构建一个并发容器,它们确实存在并且是必要的,那么您将拥有一个完全不同的界面。看看Intel的TBB和微软的PPL的并发数据结构。他们有一个专为并发使用而设计的界面,与你的 slap-a-mutex-on-it hacks 相比,它会更快并且错误更少。
Just no.
Firstly, you can't just slap a mutex on it and call it thread safe. Not only is that going to generate horrific overhead when it may well be unnecessary, but you will also break the atomicity of certain operations- for example, you can't guarantee that if I check the size of the queue and then if it's more than zero, take one off the queue- because someone may have emptied it in the meantime. Or what if I take an object off and now it's been popped off? Oops.
Thread safety is in not accessing data concurrently, not just chucking a mutex at the data structure and calling it done.
Secondly, if you are going to build a concurrent container, they do exist and they are necessary, then you have a completely different interface. Look at the concurrent data structures of Intel's TBB and Microsoft's PPL. They have an interface designed for concurrent use which is going to be faster and significantly less buggy than your slap-a-mutex-on-it hacks.