3

嗨,我确实知道计数信号量是如何工作的?请帮助我理解。

根据我的理解,如果我们将计数设置为 3,那么进程可以使用 3 个线程来访问资源。所以,这里只有 3 个线程可以访问资源。当 1 个线程离开时,另一个等待线程进来。如果我的理解是正确的,这 3 个线程也会损坏共享数据。那么它有什么用呢?

4

1 回答 1

4

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

于 2012-02-11T18:19:49.173 回答