Csinglelock有什么用

what is the use of Csinglelock?

本文关键字:什么 Csinglelock      更新时间:2023-10-16

MSDN 中提到,要锁定和解锁 CCriticalSection 对象,我们应该使用 CSingleLock。但是 CCriticalSection::lock() 和 CCriticalSection::unlock() 做同样的事情,不是吗?那么这两种方法有什么区别呢?

使用包装器将确保(几乎)无论您从锁定锁的位置做什么,当您离开函数时,它都会解锁。

考虑:

void func()
{
    lock();
    ... plenty of lines ... 
    // x = 8128 happens on a Wednesday, in a month without 
    // r in the name, only if the day is divisible by 7 and 3. 
    if (x == 8128)
       return;
    ... more lines of code ... 
    unlock();
}

因此,您的应用程序时不时地忘记解锁锁。

如果您遇到异常、使用 goto 等,这同样适用。

如果使用包装器

,则可以保证在包装器的作用域结束时调用析构函数。这对于std::stringstd::vector和锁一样有用。

当然,如果您使用例如longjmp跳出上下文,则无济于事。但是你不应该使用longjmp