Concurrent Programming - Semaphore
From SwinBrain
Contents |
Concurrent Programming - Semaphore
A semaphore (or counting semaphore) is a utility that allows only x Threads to access a shared resource. Life examples include x people sitting at a table, x people getting into a car etc.
You can check out Wikipedia a background and some examples of semephores.
Semaphore Illustration
A new semaphore is created with a certain number of tokens. In this case, 2.
A thread will come in and 'acquire' the semaphore. If there is a token available, it reduce the number and continue.
A second thread comes in and acuires the last token.
Thread 3 comes in and blocks, as there are no tokens available.
When thread 1 completes its task, it releases the token back to the semaphore.
Thread 3 can now acquire a token (depending on timing).
Thread 2 completes its task and releases it's token.
Thread 3 completes its task and releases it's token.
Pseudocode
There are two parts to a semaphore, commonly called acquire and release.
acquire
lock { while noAvailableTokens { wait } _AvailableTokens-- }
release
lock { # You could check if too many tokens have been released if _AvailableTokens == 0 { wake all waiting threads } _AvailableTokens++; }
Client note
Any code that uses a semaphore, should call the acquire inside a try block, and call the release inside the finally block. This means that any failure (in terms of an exception) still renders the semaphore usable.
try { _SomeSemaphore.Acquire(); # more code } finally { _SomeSemaphore.Release(); }







