The Interlocked Functions Program Example 1
The interlocked group of functions offers a low-level synchronization between threads that share common memory. The interlocked functions are InterlockedIncrement(), InterlockedDecrement(), InterlockedExchange(), InterlockedCompareExchange(), and InterlockedExchangeAdd(). The functions are more efficient in execution than other synchronization functions and do not deal with any kernel objects. The drawback in using them is that higher primitives such as mutex, semaphore, and event objects have to be written. The following program uses an interlocked increment to keep track of the total number of printouts made by two threads.
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.
// InterlockedIncrement example
// The interlocked functions provide a simple mechanism for synchronizing access
// to a variable that is shared by multiple threads.
// This function is atomic with respect to calls to other interlocked functions.
// Global var
volatile LONG TotalCountOfOuts = 0;
///////////// Thread Main ///////////////////////
static DWORD i;
wprintf(L" Standard output print, pass #%u\n", i);
// Increments (increases by one) the value of the specified 32-bit
// variable as an atomic operation.
// To operate on 64-bit values, use the InterlockedIncrement64 function.
dwIncre = InterlockedIncrement((LPLONG)&TotalCountOfOuts);
// The function returns the resulting incremented value.
wprintf(L" Increment value is %u\n", dwIncre);
///////////////////// Create A Child//////////////
hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadMain,(LPVOID)NULL,0,&dwId);
if(hThread != NULL)
wprintf(L"CreateThread() is OK, thread ID %u\n", dwId);
wprintf(L"CreateThread() failed, error %u\n", GetLastError());
if(CloseHandle(hThread) != 0)
wprintf(L"hThread's handle was closed successfully!\n");
wprintf(L"CloseHandle() failed, error %u\n", GetLastError());
/////// Main /////
// 500/100 (from ThreadMain())= 5; Then 5 x 2 threads = 10.
wprintf(L"Current count of the printed lines by child threads = %u\n", TotalCountOfOuts);
Build and run the project. The following screenshot is a sample output.