Semaphore Management

After one process creates a semaphore, threads in other processes must open the semaphore before they can access it. (Creating a semaphore automatically opens it for the creating process.) The open operation ensures that the process is a valid user of the semaphore. OS/2 keeps track of the number of open operations that each process performs on a semaphore. A process can have up to 65535 (64K - 1) open operations performed on a semaphore at any one time.

If a process finishes using a semaphore and will not use it again, the process should close the semaphore so that OS/2 can free the memory the semaphore is using. OS/2 returns the ERROR_SEM_BUSY error value if a thread tries to close a semaphore that has another thread in the same process still waiting for it.

If a process terminates with open semaphores, OS/2 automatically closes the semaphores for that process.

Semaphores reside in a memory buffer rather than a disk file. Therefore, when the last process that has a semaphore open exits or closes that semaphore, OS/2 frees the associated handle or name.

When an application calls a function that causes a thread to wait on a semaphore, the application can specify the amount of time for the thread to wait. When the interval elapses without the semaphore being posted or released, the function returns the ERROR_TIMEOUT error value and the thread continues running. The application can provide a specific time-out value in milliseconds, or it can specify either the SEM_INDEFINITE_WAIT or the SEM_IMMEDIATE_RETURN flag. If a thread is interrupted while it is waiting on a semaphore, the ERROR_INTERRUPT error value is returned to the caller.


[Back: Named and Anonymous Semaphores]
[Next: Using Event Semaphores]