CCriticalSection Class

Represents a "critical section" — a synchronization object that allows one thread at a time to access a resource or section of code.

class CCriticalSection : public CSyncObject

Remarks

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.

Nota

The functionality of the CCriticalSection class is provided by an actual Win32 CRITICAL_SECTION object.

Critical sections are used instead of mutexes (see CMutex) when speed is critical and the resource will not be used across process boundaries.

There are two methods for using a CCriticalSection object: stand-alone and embedded in a class.

  • Stand-alone method   To use a stand-alone CCriticalSection object, construct the CCriticalSection object when it is needed. After a successful return from the constructor, explicitly lock the object with a call to Lock. Call Unlock when you are done accessing the critical section. 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.

    A more preferable method is to use the CSingleLock class. It also has a Lock and Unlock method, but you don't have to worry about unlocking the resource if an exception occurs.

  • Embedded method   You can also share a class with multiple threads by adding a CCriticalSection-type data member to the class and locking the data member when needed.

For more information on using CCriticalSection objects, see the article Multithreading: How to Use the Synchronization Classes.

Requirements

Header: afxmt.h

See Also

Reference

CSyncObject Class

Hierarchy Chart

CMutex Class

Other Resources

CCriticalSection Members