Using Critical Section Objects Program Example
The following example shows how a thread initializes, enters, and releases a critical section. It uses the InitializeCriticalSectionAndSpinCount(), EnterCriticalSection(), LeaveCriticalSection(), and DeleteCriticalSection() functions.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
// Global variable
CRITICAL_SECTION CriticalSection;
int wmain()
{
DWORD Ret = 0;
//...
// Initialize the critical section one time only.
// Initializes a critical section object and sets the spin count for the
// critical section. Spinning means that when a thread tries to acquire
// a critical section that is locked, the thread enters a loop, checks
// to see if the lock is released, and if the lock is not released,
// the thread goes to sleep.
wprintf(LInitializing the critical section...\n);
Ret = InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x80000400);
// This function always returns a nonzero value..
wprintf(LInitializeCriticalSectionAndSpinCount() return value is %d\n, Ret);
//...
// Release resources used by the critical section object.
// Releases all resources used by an unowned critical section object.
// This function does not return a value.
wprintf(LDeleting the critical section...\n);
DeleteCriticalSection(&CriticalSection);
}
// ThreadProc() Callback Function
// An application-defined function that serves as the starting address for a thread.
DWORD WINAPI ThreadProc( LPVOID lpParameter )
{
//...
// Request ownership of the critical section.
// Waits for ownership of the specified critical section object.
// The function returns when the calling thread is granted ownership.
// This function does not return a value.
wprintf(LEntering the critical section...\n);
EnterCriticalSection(&CriticalSection);
// Access the shared resource.
wprintf(LAccessing and using the shared resources...\n);
// Release ownership of the critical section.
// This function does not return a value.
wprintf(LLeaving the critical section...\n);
LeaveCriticalSection(&CriticalSection);
//...
// The return value indicates the success or failure of this function.
return 0;
}
Build and run the project. The following screenshot is a sample output.