开发者

Const reference in getter method [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 popped 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜