Can you please review this code. I believe there is nothing wrong here.
You may esp. like to lo开发者_运维知识库ok 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;
}
In dequeue
, you return a dangling reference. Once you've pop
ped the
object, it ceases to exist.
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.
精彩评论