Can anyone tell me what is counting semaphore? what is advantage of counting semaphore? can you write a snippet code for a counting semaphore in c.
-
Have you tried googling 'counting semaphore'? – scottysmalls Jan 28 '16 at 11:33
-
Yes, i tried a lot but did not get exact benefit of counting semaphore in real time problem. Because to let all thread to access shared resource could lead to corruption. – Sumit Gemini Jan 29 '16 at 07:21
2 Answers
In cases where you have N available resources a counting semaphore can keep track of number of remaining resources. When any thread access one of the semaphores counter of semaphore will reduce by one and when a thread release the semaphore the counter will increase by one. If the counter reaches zero and a thread ask for a resource the thread will be blocked till another thread release the semaphore. A well known application of semaphore is producer-consumer. You can find a good description for producer consumer problem here: https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem It also includes the simple code you where looking for.
Also semaphores can be initialized to limit the maximum number of resources it controls. If we limit that to 1 this is called a binary semaphore which has just two states sema = 1 or sema = 0 Binary and counting semaphores are compared here: Differnce between Counting and Binary Semaphores

- 85
- 1
- 10
Counting semaphores are about as powerful as conditional variables (used in conjunction with mutexes). In many cases, the code might be simpler when it is implemented with counting semaphores rather than with condition variables (as shown in the next few examples).
Conceptually, a semaphore is a nonnegative integer count. Semaphores are typically used to coordinate access to resources, with the semaphore count initialized to the number of free resources. Threads then atomically increment the count when resources are added and atomically decrement the count when resources are removed.
When the semaphore count becomes zero, indicating that no more resources are present, threads trying to decrement the semaphore block wait until the count becomes greater than zero.
Refer to this link for example.

- 12,987
- 11
- 98
- 148