简体   繁体   English

此函数(运算符重载)线程安全吗?

[英]Is this function(operator overloading) threadsafe?

Here's the code: 这是代码:

ElementType& operator[] (int key)
{
    //something like boost::mutex::scoped_lock
    MutexLockType lock();

    if(key < 0 || key > m_bound)
        throw std::range_error("access out of bound");

    return m_elements[key];
}

No it is not because you have allowed a reference the element to leak out of the function and away from the safety of the lock. 不,不是因为您已允许引用该元素从函数中泄漏并脱离锁的安全性。

What's more, thread-safety questions are a little hard to answer without a harder specification of just what flavour of thread-safety you are desirest. 更重要的是,如果没有更严格地说明您想要什么类型的线程安全 ,则很难回答线程安全问题。 At the very least you would need to show us every other access of m_elements and m_bound . 至少您需要向我们展示m_elementsm_bound所有其他访问权限。

In this exact example you would be even more surprised when you realize that there is no lock at all, just a declaration of a lock() function that returns a LockType. 在这个确切的示例中,当您意识到根本没有锁,而只是返回一个LockType的lock()函数的声明时,您会感到更加惊讶。

Not that that it would have helped with a lock anyway. 并不是说它反而有助于锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM