views:

252

answers:

1

What is the relation ship between CRITICAL_SECTION and CCriticalSection. is CCriticalSection a wrapper of CRITICAL_SECTION?

BTW:

I think the following code is meanless because the cs is not Global, it initial every times before lock() so it can't lock the XXX , is it ?

int func
{
CCriticalSection cs;
cs.Lock();
XXX
cs.Unlock();
}

Many Thanks!

+2  A: 

Yes the MFC CCriticalSection section is just a wrapper around a Win32 CRITICAL_SECTION.

This goes for pretty much all of MFC, its a huge set of wrapper classes around standard Win32 functionality.

As to your code example, yes the use of a critical section in that context is meaningless. What a critical section does is akin to a named mutex, it ensures that a resource can only be accessed by a single thread at a time. Proper use of a critical section would be as an object accessible by multiple threads, then when using a resource which cannot be used by more than one thread at a time:

MyGlobalCS.Lock();

// Do important work on resource

MyGlobalCS.Unlock();

Also note that if its hard to get the critical section into a shared location you can use a named mutex instead.

DeusAduro
True, and it's worth noting that the one really useful thing it *could* provide, RAII, it doesn't. If you're using C++ and MFC, you *really* need to consider using boost instead.
Tim Sylvester
I would say 'alongside' not 'instead', boost certainly doesn't replace the majority of what MFC is targeted at, that being GUIs.
DeusAduro