Using the CreateSemaphore() and the related functions for thread synchronization

 

 

 

// For WinXp as a target, change appropriately

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

 

int main(void)

{

HANDLE hSemaphore;

LONG cMax = 10;

LPWSTR MySem = L"TestSem";

DWORD dwWaitResult;

 

// Create a semaphore with initial and maximum counts of 10.

hSemaphore = CreateSemaphore(

NULL, // default security attributes

cMax, // initial count

cMax, // maximum count

MySem); // named semaphore

 

if (hSemaphore == NULL)

{

printf("CreateSemaphore() error: %d\n", GetLastError());

}

else

printf("CreateSemaphore() is OK\n");

 

// Example...

// Before any thread of the process creates a new window for example, it uses the WaitForSingleObject()

// function to determine whether the semaphore's current count permits the creation of additional windows.

// The wait function's time-out parameter is set to zero, so the function returns immediately if the semaphore is nonsignaled.

// Try to enter the semaphore gate.

dwWaitResult = WaitForSingleObject(

hSemaphore, // handle to semaphore

0L); // zero-second time-out interval

 

switch (dwWaitResult)

{

// The semaphore object was signaled.

case WAIT_OBJECT_0: printf("The semaphore object was signaled. Can open another window..\n");

// OK to open another window.

break;

// Semaphore was nonsignaled, so a time-out occurred.

case WAIT_TIMEOUT: printf("The semaphore object was nonsignaled, so a time-out...Can't open another window\n");

// Cannot open another window.

break;

}

 

// Increment the count of the semaphore.

if (!ReleaseSemaphore(

hSemaphore, // handle to semaphore

1, // increase count by one

NULL)) // not interested in previous count

{

printf("ReleaseSemaphore() error: %u\n", GetLastError());

}

else

{

printf("ReleaseSemaphore() is OK\n");

}

 

return 0;

}

 

Output example:

 

CreateSemaphore() is OK

The semaphore object was signaled. Can open another window..

ReleaseSemaphore() 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 CreateSemaphore() related functions in C program example

To show: The Windows process and thread related functions - creating the semaphore object for thread synchronization

 

 

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