liveBook · Manning

Sync package

As explained in Learn Concurrent Programming with Go

sync is a Go standard-library package that provides synchronization primitives and related concurrency utilities.

The sync package provides Go’s mutex synchronization primitive. A mutex lets only one goroutine enter a critical section at a time, preventing concurrent updates from producing a race condition. section 4.1.1

Use a mutex around every access to shared state:

  • Create an initially unlocked sync.Mutex. section 4.1.1
  • Call Lock before entering the critical section. section 4.1.1
  • Call Unlock immediately after the protected operation; waiting goroutines then compete for the mutex. section 4.1.1

Protecting a shared account balance

Two goroutines repeatedly add to and subtract from a shared money variable. Passing both a pointer to the variable and a shared mutex ensures that each update occurs alone; the demonstrated result is 100.

How Learn Concurrent Programming with Go covers it

How deep it goes
Defines mutual exclusion and demonstrates Lock and Unlock, stopping short of broader synchronization utilities.
Examples
Uses concurrent Stingy and Spendy functions to protect repeated additions and subtractions from a shared account balance.
What it assumes
Assumes goroutines and shared variables, while defining mutexes and critical sections before demonstrating their use.
What you can do after
Apply it via Go’s sync.Mutex to serialize access to shared state and avoid race conditions.
How it connects
Connects mutexes with goroutines, critical sections, shared memory, and race conditions.

Also explained in

Compare how 3 books explain sync package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.