什么是计数信号量? [英] what is Counting Semaphore?

查看:125
本文介绍了什么是计数信号量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

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

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.

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

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.

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

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.

  • Wikipedia: Semaphore - Important Observations

这篇关于什么是计数信号量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆