The semaphore package
This last section of this chapter presents the semaphore
package, which is provided by the Go team. A semaphore is a construct that can limit or control the access to a shared resource. As we are talking about Go, a semaphore can limit the access of goroutines to a shared resource but originally, semaphores were used for limiting access to threads. Semaphores can have weights that limit the number of threads or goroutines that can have access to a resource.
The process is supported via the Acquire()
and Release()
methods, which are defined as follows:
func (s *Weighted) Acquire(ctx context.Context, n int64) error
func (s *Weighted) Release(n int64)
The second parameter of Acquire()
defines the weight of the semaphore.
As we are going an external package, we need to put the code inside ~/go/src
in order to use Go modules: ~/go/src/github.com/mactsouk/semaphore
. Now, let us present the code of semaphore.go
, which shows an implementation of...