O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How it works...

The synchronization primitive Mutex is provided by the package sync. The Mutex works as a lock above the secured section or resource. Once the goroutine calls Lock on the Mutex and the Mutex is in the unlocked state, the Mutex becomes locked and the goroutine gets exclusive access to the critical section. In case the Mutex is in the locked state, the goroutine calls the Lock method. This goroutine is blocked and needs to wait until the Mutex gets unlocked again. 

Note that in the example, we use the Mutex to synchronize access on a slice primitive, which is considered to be unsafe for the concurrent use.

The important fact is that the Mutex cannot be copied after its first use.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required