Re: CSingleLock - known behaviour?
On Thu, 26 Jun 2008 00:06:49 -0400, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
What is interesting is that this whole discussion goes away if you just use the raw
synchronization objects, which always do the right thing in the right way under all the
scenarios that are interesting.
But then you have problems with exception safety and early returns. You can
avoid those issues by using RAII lock classes. Otherwise, you might as well
program in C.
Or even possible (I exclude deadlock scenarios, in which
no implementation, even the raw API, can compensate for an incorrect locking strategy).
So why the fixation on a set of known-to-be-broken classes?
I'm not fixated on them; as I've said many times, I've never used the MFC
sync classes.
Don't say "the destructors handle the unlocking" because you can handle that quite simply.
Instead of writing
{
CSingleLock lock(&mutex);
lock.Lock();
If I were to use CSingleLock for the first time ever, I would write:
CSingleLock lock(&mutex, true);
and omit the Lock call.
....
} // implict Unlock here
you can write
__try {
::WaitForCriticalSection(mutexhandle, INFINITE); // error handling left EFTR
}
__finally
{
::ReleaseMutex(mutexhandle);
}
or, if you are using MFC, where _try/__finally are usually diagnosed incorrectly by the
compiler as Not Playing Well With Others
try {
::WaitForSingleObject(mutexhandle, INFINITE); // errors EFTR
DoSomething();
::ReleaseMutex(mutexhandle);
}
catch(CException * e)
{
::ReleaseMutex(mutexhandle);
throw;
}
Writing try/catch blocks clutters the code in a big way, and you have to
duplicate code as you've done above to handle the exception and
non-exception paths, which is error-prone. Q: Why doesn't C++ have finally?
A: Because it has RAII. See Stroustrup:
Why doesn't C++ provide a "finally" construct?
http://www.research.att.com/~bs/bs_faq2.html#finally
I've said many times that the degree to which you're using C++ exceptions
effectively is inversely proportional to the number of try/catch blocks you
write, and the reason for that is the use of classes with destructors
eliminates the need to write try/catch in most cases.
--
Doug Harrison
Visual C++ MVP