Lesson 31. Concurrent state

 

After reading lesson 31, you’ll be able to

  • Keep state safe
  • Use mutexes and reply channels
  • Employ service loops

Here we are back in the gopher factory. The busy gophers are still building things, but several of the production lines are running low on stock, so they need to order more.

Unfortunately, this is an old-fashioned factory that only has a single shared phone landline to the outside world. All the production lines have their own handset, though. A gopher picks up the phone to place an order, but as she starts speaking, another gopher picks up another handset and starts dialing, interfering with the first gopher. Then another does the same thing and they all get very confused and none of them manage to place any order at all. If only they could agree to use the phone one at time!

Shared values in a Go programs are a bit like this shared phone. If two or more goroutines try to use a shared value at the same time, things can go wrong. It might turn out okay. Perhaps no two gophers will ever try to use the phone at the same time. But things can go wrong in all kinds of ways.

Perhaps two gophers talking at the same time confuse the seller at the other end of the line, and they end up ordering the wrong things, or the wrong quantity of things, or something else about the order goes wrong. There’s no way to know—all bets are off.

31.1. Mutexes

31.2. Long-lived workers

Summary