The Interlocked Functions Program Example 3
The next program demonstrates how mutual exclusion can be achieved by using the InterlockedIncrement() and the InterlockedDecrement() functions. The code makes sure that only one thread is executing the critical section of code at any time. The problem is that the threads may become starved. A starved thread is one in which there is no guarantee that the thread will actually enter the critical section, just waiting, hence cannot complete its task.
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.
// Example demonstrating the mutual exclusion (MutEx)
// Global variable, no need for volatile
LONG TotalThreadCount = 0;
///// Thread Main ///////
void ThreadMain(char *threadName)
// Let give some limit...
for(i = 0;i < 10;i++)
while( InterlockedIncrement((LPLONG)&TotalThreadCount) !=1 )
// Critical section code should be here
wprintf(L"%S, in critical section, doing my task...\n", threadName);
// May give some time to simulate the task need to be completed
// Critical section ends
/////////// Create A Child //////////////
void CreateChildThread(char *name)
hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadMain,(LPVOID)name,0,&dwId);
if(hThread != NULL)
wprintf(L"CreateThread() is OK, thread id is %u\n", dwId);
wprintf(L"CreateThread() failed, error %u\n", GetLastError());
if(CloseHandle(hThread) != 0)
wprintf(L"hThread handle closed successfully!\n");
wprintf(L"Failed to close hThread handle, error %u\n", GetLastError());
//////////////////// Main ///////////////////////
Build and run the project. The following screenshot is a sample output.