关于InitializeCriticalSection 函数的解释
The InitializeCriticalSection function initializes a critical section object.
定义void InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection);
参数lpCriticalSection[out] Pointer to the critical section object.返回值Thisfunction does not return a value.
In low memory situations, InitializeCriticalSection can raise a STATUS_NO_MEMORY exception.
说明The threads of a single process can use a critical section object formutual-exclusion synchronization. There is no guarantee about the order inwhich threads will obtain ownership of the critical section, however, thesystem will be fair to all threads.
The process is responsible for allocating the memory used by a critical sectionobject, which it can do by declaring a variable of type CRITICAL_SECTION.Before using a critical section, some thread of the process must call theInitializeCriticalSection or InitializeCriticalSectionAndSpinCount function toinitialize the object.
After a critical section object has been initialized, the threads of theprocess can specify the object in the EnterCriticalSection,TryEnterCriticalSection, or LeaveCriticalSection function to provide mutuallyexclusive access to a shared resource. For similar synchronization between thethreads of different processes, use a mutex object.
A critical section object cannot be moved or copied. The process must also notmodify the object, but must treat it as logically opaque. Use only the criticalsection functions to manage critical section objects. When you have finishedusing the critical section, call the DeleteCriticalSection function.
A critical section object must be deleted before it can be reinitialized.Initializing a critical section that has already been initialized results inundefined behavior.
调用实例可供参考,如下:
msdn上的例子
Using Critical Section Objects:
The following example shows how a thread initializes, enters, and leaves a critical section. As with the mutex example (see Using Mutex Objects), this example uses structured exception-handling syntax to ensure that the thread calls the LeaveCriticalSection function to release its ownership of the critical section object.
CRITICAL_SECTION CriticalSection;
// Initialize the critical section.
InitializeCriticalSection(&CriticalSection);
// Request ownership of the critical section.
__try
{
EnterCriticalSection(&CriticalSection);
// Access the shared resource.
}
__finally
{
// Release ownership of the critical section.
LeaveCriticalSection(&CriticalSection);
// Release resources used by the critical section object.
DeleteCriticalSection(&CriticalSection)
}