Semaphores

Semaphores are tools used to solve concurrency issues. They have a certain number of available quotas that is used to limit the access to resources; also, various threads can request one or more quotas from it, and then release them when they are done. If the number of quotas available is one, it means that the semaphore supports only one access at time, with a behavior similar to mutexes. If the quota is more than one, we are referring to the most common type—the weighted semaphore.

In Go, a semaphore can be implemented using a channel with a capacity equal to the quotas, where you send a message to the channel to acquire a quota, and receive one from it to release:

type sem chan struct{}

func (s sem) Acquire() {
s <- struct{}{}
}

func (s sem) Relase() {
<-s
}

The preceding code shows us how to implement a semaphore using a channel in a few lines. Here's an example of how to use it:

func main() {
s := make(sem, 5)
for i := 0; i < 10; i++ {
go func(i int) {
s.Acquire()
fmt.Println(i, "start")
time.Sleep(time.Second)
fmt.Println(i, "end")
s.Relase()
}(i)
}
time.Sleep(time.Second * 3)
}

The full example is available at https://play.golang.org/p/BR5GN2QopjQ.

We can see from the previous example how the program serves some requests on the first round of acquisition, and the others on the second round, not allowing more than five executions at the same time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.158.165