A semaphore caps how many concurrent actors can use a resource.
Unlike a mutex (exclusive access), a semaphore hands out a fixed number of permits. Think of a bucket of tokens: each visitor acquires a token; when the bucket is empty, new acquires block until someone adds permits or releases them.
Below we use the classic two-thread print puzzle to see how that feels in code.
信号量(Semaphore)是一种对资源并发访问控制的方式。
区别于互斥锁(Mutex)是对共享资源的独占访问,Semaphore允许指定多个并发访问共享资源。
就是说Semaphore像一个持有令牌(permit/token)的桶,每一个并发访问需要持有(acquire)一个令牌来访问共享资源,
当没有令牌时,没法访问共享资源,直到有新的令牌加入(add)或者原来发出的令牌放回(release)桶中。
接下来,我们尝试用通过用它来实现两个线程交替打印1和2,来更直观了解如何使用semaphore
Read More
Read More