Using the critical section object related functions for thread synchronization

 

 

 

// For WinXp as a target, change appropriately

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

 

// Global variable

CRITICAL_SECTION CriticalSection;

 

// Application defined function...

DWORD WINAPI ThreadProc(LPVOID lpParameter)

{

// TODO: Other tasks...

printf("In ThreadProc(), application defined function...\n");

printf("EnterCriticalSection() and LeaveCriticalSection().\n");

// Request ownership of the critical section.

EnterCriticalSection(&CriticalSection);

// TODO: For example, access the shared resource...

 

// Release ownership of the critical section.

LeaveCriticalSection(&CriticalSection);

// TODO: Other tasks...

return 0;

}

 

int main(void)

{

// TODO: Other tasks...

printf("In main()...\n");

printf("InitializeCriticalSectionAndSpinCount() and after\n");

printf("return from function call use DeleteCriticalSection()...\n\n");

 

// Initialize the critical section one time only...

if (!InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x80000400))

// just return or other error processing...

printf("InitializeCriticalSectionAndSpinCount() failed, error: %d.\n", GetLastError());

else

printf("InitializeCriticalSectionAndSpinCount() is OK.\n");

 

// Release resources used by the critical section object.

DeleteCriticalSection(&CriticalSection);

return 0;

}

 

Output example:

 

In main()...

InitializeCriticalSectionAndSpinCount() and after

return from function call use DeleteCriticalSection()...

InitializeCriticalSectionAndSpinCount() is OK.

Press any key to continue . . .

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Target platform: none, just for learning and fun

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged

To do: Using the critical section object related functions for thread synchronization

To show: The Windows process and thread related functions usage in Win32 system programming

 

 

C and C++ Programming Resources | C & C++ Code Example Index