When a process no longer requires access to a mutex semaphore, it can close the semaphore by calling DosCloseMutexSem. However, if a process ends without closing an open semaphore, the semaphore is closed by OS/2.
The following code fragment closes a mutex semaphore. Assume that the handle of the semaphore has been placed into hmtx already.
#define INCL_DOSSEMAPHORES /* Semaphore values */ #include <os2.h> #include <stdio.h> HMTX hmtx; /* Mutex semaphore handle */ APIRET ulrc; /* Return code */ ulrc = DosCloseMutexSem(hmtx); if (ulrc != 0) { printf("DosCloseMutexSem error: return code = %ld", ulrc); return; }
Each call to DosCloseMutexSem decrements the usage count of the semaphore. This count is initialized to 1 when the semaphore is created and is incremented by each call to DosOpenMutexSem. When the usage count reaches 0, the semaphore is deleted by OS/2.
The call to DosCloseMutexSem that decrements the usage count to 0 and causes the semaphore to be deleted is referred to as the final close. The final close will not succeed if either of the following conditions exists:
For both conditions, ERROR_SEM_BUSY is returned.
ERROR_SEM_BUSY is also returned if a thread tries to close a mutex semaphore that it still owns. The thread must first relinquish ownership of the semaphore by calling DosReleaseMutexSem.
Calls to DosOpenMutexSem and DosCloseMutexSem can be nested, but the usage count for a semaphore cannot exceed 65535. If an attempt is made to exceed this number, ERROR_TOO_MANY_OPENS is returned.