Windows Thread Synchronization 37






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.


The Interlocked Functions Program Example 3: Creating new empty console application in Visual C++ .NET


Then, add the source file and give it a suitable name.


The Interlocked Functions Program Example 3: Adding new C++ source file


Next, add the following source code.


// Example demonstrating the mutual exclusion (MutEx)

#include <windows.h>

#include <stdio.h>


// Global variable, no need for volatile

LONG TotalThreadCount = 0;


///// Thread Main ///////

void ThreadMain(char *threadName)


      DWORD i;


      // 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)


      HANDLE hThread;

      DWORD dwId;


    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 ///////////////////////

int wmain(void)








    return 0;



Build and run the project. The following screenshot is a sample output.


The Interlocked Functions Program Example 3: A sample console program output





< Thread Synchronization 36 | Thread Synchronization Programming | Win32 Programming | Thread Synchronization 38 >