Semaphore - What is the use of initial count?

Sandbox picture Sandbox · Jan 16, 2011 · Viewed 32.5k times · Source

http://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim.aspx

To create a semaphore, I need to provide an initial count and maximum count. MSDN states that an initial count is -

The initial number of requests for the semaphore that can be granted concurrently.

While it states that maximum count is

The maximum number of requests for the semaphore that can be granted concurrently.

I can understand that the maximum count is the maximum number of threads that can access a resource concurrently. But, what is the use of initial count?

If I create a semaphore with an initial count of 0 and a maximum count of 2, none of my threadpool threads are able to access the resource. If I set the initial count as 1 and maximum count as 2 then only thread pool thread can access the resource. It is only when I set both initial count and maximum count as 2, 2 threads are able to access the resource concurrently. So, I am really confused about the significance of initial count?

SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 2); //all threadpool threads wait
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 2);//only one thread has access to the resource at a time
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2, 2);//two threadpool threads can access the resource concurrently

Answer

SVGreg picture SVGreg · Jan 16, 2011

Yes, when the initial number sets to 0 - all threads will be waiting while you increment the "CurrentCount" property. You can do it with Release() or Release(Int32).

Release(...) - will increment the semaphore counter

Wait(...) - will decrement it

You can't increment the counter ("CurrentCount" property) greater than maximum count which you set in initialization.

For example:

SemaphoreSlim^ s = gcnew SemaphoreSlim(0,2); //s->CurrentCount = 0
s->Release(2); //s->CurrentCount = 2
...

s->Wait(); //Ok. s->CurrentCount = 1
...

s->Wait(); //Ok. s->CurrentCount = 0
...

s->Wait(); //Will be blocked until any of the threads calls Release()