what is Counting Semaphore?

社会主义新天地 提交于 2019-12-10 20:22:21

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/9242539/what-is-counting-semaphore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!