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 (https://golang.org/pkg/sync/) 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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.