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.

Image:Semaphore 1.png

A thread will come in and 'acquire' the semaphore. If there is a token available, it reduce the number and continue.

Image:Semaphore 2.png

A second thread comes in and acuires the last token.

Image:Semaphore 3.png

Thread 3 comes in and blocks, as there are no tokens available.

Image:Semaphore 4.png

When thread 1 completes its task, it releases the token back to the semaphore.

Image:Semaphore 5.png

Thread 3 can now acquire a token (depending on timing).

Image:Semaphore 6.png

Thread 2 completes its task and releases it's token.

Image:Semaphore 7.png

Thread 3 completes its task and releases it's token.

Image:Semaphore 8.png

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();
}