The sync package

There are instances when accessing shared values using traditional methods are simpler and more appropriate then the use of channels. The sync package ( provides several synchronization primitives including mutual exclusion (mutex) locks and synchronization barriers for safe access to shared values, as discussed in this section.

Synchronizing with mutex locks

Mutex locks allow serial access of shared resources by causing goroutines to block and wait until locks are released. The following sample illustrates a typical code scenario with the Service type, which must be started before it is ready to be used. After the service has started, the code updates an internal bool variable, started, to store its ...

Get Learning Go Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.