Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is Counting Semaphore?

Hi I did get how the Counting Semaphore works? Please help me in understanding.

As per my understanding if we set count as 3, then process can use 3 threads to access the resource. so, here just 3 threads have access on the resource. When 1 thread leaves the other waiting thread comes in. If my understanding is correct, these 3 thread can corrupt shared data too. Then what is use of it?

like image 716
user900721 Avatar asked Oct 15 '25 07:10

user900721


1 Answers

Your observations are correct; typically a resource either needs to be restricted to one thread (e.g. it is being written to), or is safe to use with an unlimited number of threads (e.g. it is read-only). Restricting a resource to be used by say 5 threads is rarely useful.

Thus a counting semaphore with count N is most often used to restrict access to a pool of N resources...when the count reaches zero the next thread has to wait to obtain a resource from the pool.

However, I don't commonly find this useful in practice because simply controlling the number of threads accessing a pool of resources isn't sufficient, you need to manage the resources themselves as well. So I typically end up with a blocking queue containing the managed resources that threads can take from. When a thread is done with a resource, it returns that resource (e.g. an object) to the queue so that a waiting thread can take it.

The queue might internally use a semaphore to control access to the internal buffer, but that is usually encapsulated from the user of the queue.

See also

  • Wikipedia: Semaphore - Important Observations
like image 88
Mark Peters Avatar answered Oct 17 '25 13:10

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!