安全锁定/解锁,无需护目镜

Mir*_*pas 1 c++ locking

我必须处理设计限制(依赖性问题)以不对互斥锁使用范围保护.

示例代码:

template<typename MutexType>
class Test
{
    MutexType myMutex;

public:
    void f()
    {
        myMutex.Lock();
        //code with many returns here depending on conditions
        myMutex.Unlock();
    }
};
Run Code Online (Sandbox Code Playgroud)

是否有其他安全的方法来处理没有范围保护的多次退货?在概念被广泛使用之前,这是如何工作的?是goto一个不错的选择,而不是return考虑禁用例外?

Rei*_*ica 6

正如@VladLazarenko在评论中建议的那样,最好的方法就是为此编写自己的范围保护.

但是,如果出于一些不可能的原因,您可以简单地将所有内容移动//code with many returns here depending on conditions到一个单独的函数中,并在调用Lock()Unlock()调用之间调用该函数.

你提到你有异常禁用; 如果不是这种情况,上面的解决方案(嵌套函数)将需要try ... catch外部函数中的一个额外的构造,那么它也可以工作.