July 2019
Intermediate to advanced
458 pages
12h 12m
English
The most simple implementation of locker is sync.Mutex. Since its method has a pointer receiver, it should not be copied or passed around by value. The Lock() method takes control of the mutex if possible, or blocks the goroutine until the mutex becomes available. The Unlock() method releases the mutex and it returns a runtime error if called on a non-locked one.
Here is a simple example in which we launch a bunch of goroutines using the lock to see which is executed first:
func main() { var m sync.Mutex done := make(chan struct{}, 10) for i := 0; i < cap(done); i++ { go func(i int, l sync.Locker) { l.Lock() defer l.Unlock() fmt.Println(i) time.Sleep(time.Millisecond * 10) done <- struct{}{} }(i, &m) } for i := 0; i < cap(done); i++ ...Read now
Unlock full access