Semaphore - What is the use of initial count?

Posted by Sandbox on Stack Overflow See other posts from Stack Overflow or by Sandbox
Published on 2011-01-16T17:03:47Z Indexed on 2011/01/16 17:53 UTC
Read the original article Hit count: 173

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading