Semaphore - What is the use of initial count? Semaphore - What is the use of initial count? multithreading multithreading

Semaphore - What is the use of initial count?


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 = 0s->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()


So, I am really confused about the significance of initial count?

One important point that may help here is that Wait decrements the semaphore count and Release increments it.

initialCount is the number of resource accesses that will be allowed immediately. Or, in other words, it is the number of times Wait can be called without blocking immediately after the semaphore was instantiated.

maximumCount is the highest count the semaphore can obtain. It is the number of times Release can be called without throwing an exception assuming initialCount count was zero. If initialCount is set to the same value as maximumCount then calling Release immediately after the semaphore was instantiated will throw an exception.


How many threads do you want to be able to access resource at once? Set your initial count to that number. If that number is never going to increase throughout the life of the program, set your max count to that number too. That way, if you have a programming error in how you release the resource, your program will crash and let you know.

(There are two constructors: one that takes only an initial value, and one that additionally takes the max count. Use whichever is appropriate.)