信号量和同步 [英] Semaphore and synchronization

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

问题描述

我从javadocs中的信号量描述中无法完全理解以下内容.

I could not quite understand the following from the semaphore description in javadocs.

请注意,没有同步锁 当调用generate()时保持的状态 会阻止物品被 回到游泳池. 信号量 封装同步 需要限制对池的访问, 与任何同步分开 需要保持一致性 池本身.

Note that no synchronization lock is held when acquire() is called as that would prevent an item from being returned to the pool. The semaphore encapsulates the synchronization needed to restrict access to the pool, separately from any synchronization needed to maintain the consistency of the pool itself.

有人可以帮我理解这一点及其含义吗?

Can someone please help me understand this and its implications.

推荐答案

信号量是可用资源池深度的限制器;例如,一个容量为10的信号量最多允许10个线程一次获取它,而任何其他试图获取它的线程都将阻塞,直到其他线程之一释放它为止.

A semaphore acts as a limiter of available resource pool depth; for example, a semaphore with a capacity of 10 allows a maximum of 10 threads to acquire it at once, and any further threads that attempt to acquire it will block until one of the other threads releases it.

这与普通的互斥或监视器锁定有些不同,后者通常用于防止多个线程同时修改相同的变量并导致不一致的结果或程序状态.

This is somewhat different from ordinary mutual exclusion or monitor locking, which is typically used to prevent more than one thread from simultaneously modifying the same variables and causing inconsistent results or program state.

例如,考虑一个连接池,其中限制为10个连接.每个需要连接的线程都将在使用连接的过程中获取信号量(这样可以防止过多的线程一次请求连接),但是当从内部连接中取出连接时,池对象还必须使用同步块或方法收集或放回它们,以防止丢失连接跟踪或由于它们同时询问而将同一连接错误地传递给两个不同的线程.

Consider, for example, a connection pool with a limit of 10 connections in it. Each thread that needs a connection will acquire the semaphore for the duration of its use of a connection (which prevents too many threads asking for connections at once), but the pool object must also use synchronized blocks or methods when taking connections out of its internal collection or putting them back in, to prevent such things as losing track of connections or mistakenly handing the same connection to two different threads because they asked simultaneously.

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

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