CCriticalSection

An object of class CCriticalSection represents a “critical section” — a synchronization object that allows one thread at a time to access a resource or section of code. Critical sections are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CCriticalSection object to control the linked list, only one thread at a time can gain access to the list.

Critical sections are used instead of mutexes when speed is critical and the resource will not be used across process boundaries. For more information on using mutexes in MFC, see CMutex.

To use a CCriticalSection object, construct the CCriticalSection object when it is needed. You can then access the critical section when the constructor returns. Call Unlock when you are done accessing the critical section.

To access a resource controlled by a CCriticalSection object in this manner, first create a variable of type CSingleLock****in your resource’s access member function. Then call the lock object’s Lock member function (for example, CSingleLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, use the lock object’s Unlock member function (for example, CSingleLock::Unlock), or allow the lock object to fall out of scope.

Alternatively, you can create a CCriticalSection object stand-alone, and access it explicitly before attempting to access the controlled resource. This method, while clearer to someone reading your source code, is more prone to error as you must remember to lock and unlock the critical section before and after access.

For more information on using CCriticalSection objects, see the article in Visual C++ Programmer's Guide.

#include <afxmt.h>

Class MembersBase ClassHierarchy Chart

Sample   

See Also   CMutex