Re: CSingleLock - known behaviour?
On Wed, 25 Jun 2008 02:01:51 -0700 (PDT), neilsolent
<neil@solenttechnology.co.uk> wrote:
In my multi-threaded program, a thread may call CSingeLock::Lock()
twice on the same underlying Critical Section. I was expecting the
second Lock() call to do nothing if the object is already locked.
However, if the CS was already locked, it seems that the second Lock()
call has the effect of permanently locking the CS. If I then call
Unlock() multiple times, or even let the CSingleLock stack object go
out of scope - still the CS is locked.
Has anyone else seen this before?
Is this known (bad) behaviour of CSingleLock?
Obvious workaround - call IsLocked() before calling Lock()..
I think it would be very strange for you to logically not know whether or
not a Lock object is locked or not.
..BUT.. unless I am missing something - programmers should be aware of
this nasty gotcha !
Mutexes in windows are recursive; MFC Lock types are not and will assert in
debug mode if you attempt to lock a lock that is already locked. It should
be exceedingly rare to call Lock/Unlock on a lock object. The vast majority
of the time, the RAII usage should be all you need, e.g.
void f()
{
CSingleLock lk(x); // See below...
...
}
Quiz: What's wrong with this function, and how would you fix it? (Hint: It
demonstrates a truly glaring flaw in the design of CSingleLock, one of many
in the design of the MFC synchronization classes, which are IMO the most
error-ridden in all of MFC.)
--
Doug Harrison
Visual C++ MVP