It is mentioned in MSDN, that to lock and Unlock CCriticalSection object, we should use CSingleLock. But CCriticalSection::lock() and CCriticalSection::unlock() does the same thing, doesn't it? Then What is the difference between both the methods?
Asked
Active
Viewed 1,054 times
2
-
4It's too large a subject for a simple answer, but you should learn about [exception safety](http://en.wikipedia.org/wiki/Exception_safety) and [RAII](http://stackoverflow.com/questions/2321511). What would happen if something threw an exception between `lock` and `unlock`? How is a destructor different from an explicit function call? – Mike Seymour Feb 03 '15 at 07:28
1 Answers
1
Using a wrapper will ensure that (almost) no matter what you do from the point where you are locking the lock, when you leave the function, it will unlock.
Consider:
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();
}
So, once every now and again, your application forgets to unlock the lock.
The same applies if you get an exception, use goto, etc.
If you use a wrapper, you are guaranteed that the destructor will be called when the scope of the wrapper ends. This is just as useful for std::string
or std::vector
as it is for locks.
Of course, it won't help if you use for example longjmp
to jump out of the context. But then you shouldn't be using longjmp
!

Mats Petersson
- 126,704
- 14
- 140
- 227