Semaphores

In the previous chapter, we saw how it is possible to use channels to create weighted semaphores. There is a better implementation in the experimental sync package. This can be found at: golang.org/x/sync/semaphore.

This implementation makes it possible to create a new semaphore, specifying the weight with semaphore.NewWeighted.

Quotas can be acquired using the Acquire method, specifying how many quotas you want to acquire. These can be released using the Release method, as shown in the following example:

func main() {
s := semaphore.NewWeighted(int64(10))
ctx := context.Background()
for i := 0; i < 20; i++ {
if err := s.Acquire(ctx, 1); err != nil {
log.Fatal(err)
}
go func(i int) {
fmt.Println(i)
s.Release(1)
}(i)
}
time.Sleep(time.Second)
}

Acquiring quotas requires another argument besides the number, which is context.Context. This is another concurrency tool available in Go and we are going to see how to use this in the next chapter.

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

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