Mutex semaphores are created by calling DosCreateMutexSem. This function also opens the semaphore for the calling process and its threads.
When a mutex semaphore is created, a flag is set to specify the initial state of the semaphore, owned or unowned. If the semaphore is owned by a thread, other threads requesting the semaphore are blocked. If the semaphore is unowned-not owned by any thread- then any thread requesting ownership will be granted ownership immediately.
If the calling thread sets the initial state to owned, it owns the semaphore as soon as OS/2 creates the semaphore and can proceed to access the resource that the semaphore was created to protect.
If the semaphore is unowned, any thread in the creating process can subsequently request ownership of the semaphore by calling DosRequestMutexSem. Threads in other processes can gain ownership of the semaphore, but they must call DosOpenMutexSem to acquire access to the semaphore before they can call DosRequestMutexSem.
Mutex semaphores can be defined as either private or shared.
The following code fragment creates a mutex semaphore:
#define INCL_DOSSEMAPHORES /* Semaphore values */ #include <os2.h> HMTX hmtxProtFile; DosCreateMutexSem("\\sem32\\ProtFile", /* Named-shared semaphore */ &hmtxProtFile, 0, FALSE); /* Initially unowned */ . . /* Get data to write to shared file. */ .
There is a system-wide limit of 65536 shared semaphores (including mutex, event, and muxwait semaphores); in addition, each process can have up to 65536 private semaphores.
OS/2 maintains a usage count for each semaphore. DosCreateMutexSem initializes the usage count to 1. Thereafter, each call to DosOpenMutexSem increments the count, and each call to DosCloseMutexSem decrements it.