February 2019
Intermediate to advanced
450 pages
11h 59m
English
The sync package of Go's standard library provides additional synchronization features that aren't included in the language itself. Its additions to concurrency management include Mutex, WaitGroup, and Once, which we'll look at briefly.
Mutex is used when you want to ensure mutual exclusion—that is, if you only want one goroutine to access a piece of data at a time (to avoid potential conflicts). The key methods are Lock() and Unlock(), which surround the section of code that should never be executed concurrently. If a second goroutine attempts to enter the section, it will block until the lock is released:
var vals map[string]stringvar lock sync.Mutexfunc Get(key string) string { lock.Lock() defer lock.Unlock() return vals[key] ...Read now
Unlock full access