Summary

In this chapter, we saw the tools that are available in the Go standard package for synchronization. They are located in two packages: sync, which provides high-level tools such as mutexes, and sync/atomic, which executes low-level operations.

First, we saw how to synchronize data using lockers. We saw how to use sync.Mutex to lock a resource regardless of the operation type, and sync.RWMutex to allow for concurrent readings and blocking writes. We should be careful using the second one because writes could be delayed by consecutive readings.

Next, we saw how to keep track of running operations in order to wait for the end of a series of goroutines, using sync.WaitGroup. This acts as a thread-safe counter for current goroutines and makes it possible to put the current goroutine to sleep until it reaches zero, using the Wait method.

Furthermore, we checked the sync.Once structure used to execute a functionality once, which allows the implementation of a thread-safe singleton, for instance. Then we used sync.Pool to reuse instances instead of creating new ones when possible. The only thing that a pool needs is the function that returns the new instance.

The sync.Condition struct represents a specific condition and uses a locker to change it, allowing a goroutine to wait for the change. This can be delivered to a single goroutine using Signal, or to all goroutines using Broadcast. The package also offers a thread-safe version of sync.Map.

Finally, we checked out the functionalities of atomic, which are mostly integer thread-safe operations: loading, saving, adding, swapping, and CAS. We saw also atomic.Value, which that makes it possible to change the value of an interface concurrently and does not allow it to change type after the first change.

The next chapter will be about the latest element introduced in Go concurrency: Context, which is an interface that handles deadlines, cancellations, and much more.

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

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