什么是计数信号量?

发布于 2025-01-04 20:09:21 字数 167 浏览 1 评论 0原文

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一笑百媚生 2025-01-11 20:09:21

你的观察是正确的;通常,一种资源要么需要限制为一个线程(例如,它正在被写入),要么可以安全地与无限数量的线程一起使用(例如,它是只读的)。限制资源由 5 个线程使用几乎没有用处。

因此,计数为 N 的计数信号量最常用于限制对 N 资源池的访问...当计数达到零时,下一个线程必须等待获取池中的资源。

但是,我通常认为这在实践中没有用,因为仅仅控制访问资源池的线程数是不够的,您还需要管理资源本身。因此,我通常会得到一个阻塞队列,其中包含线程可以从中获取的托管资源。当线程使用完资源后,它会将该资源(例如对象)返回到队列,以便等待的线程可以获取它。

队列可能在内部使用信号量来控制对内部缓冲区的访问,但这通常是从队列的用户封装的。

另请参阅

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文