Re: CSingleLock - known behaviour?
On Thu, 26 Jun 2008 00:06:49 -0400, Joseph M. Newcomer
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
Don't say "the destructors handle the unlocking" because you can handle that quite simply.
Instead of writing
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
::WaitForCriticalSection(mutexhandle, INFINITE); // error handling left EFTR
or, if you are using MFC, where _try/__finally are usually diagnosed incorrectly by the
compiler as Not Playing Well With Others
::WaitForSingleObject(mutexhandle, INFINITE); // errors EFTR
catch(CException * e)
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?
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.
Visual C++ MVP