Lesson 30. Goroutines and concurrency

 

After reading lesson 30, you’ll be able to

  • Start a goroutine
  • Use channels to communicate
  • Understand channel pipelines

Look, it’s a gopher factory! All the gophers are busy building things. Well, almost all. Over in the corner is a sleeping gopher—or maybe he’s deep in thought. Here’s an important gopher: she’s giving orders to other gophers. They run around and do her bidding, tell others what to do, and eventually report back their findings to her. Some gophers are sending things from the factory. Others are receiving things sent from outside.

Until now, all the Go we’ve written has been like a single gopher in this factory, busy with her own tasks and not bothering with anyone else’s. Go programs are more often like a whole factory, with many independent tasks all doing their own thing, but communicating with each other towards some common goal. These concurrent tasks might include fetching data from a web server, computing millions of digits of pi, or controlling a robot arm.

In Go, an independently running task is known as a goroutine. In this lesson, you’ll learn how to start as many goroutines as you like and communicate between them with channels. Goroutines are similar to coroutines, fibers, processes, or threads in other languages, although they’re not quite the same as any of those. They’re very efficient to create, and Go makes it straightforward to coordinate many concurrent operations.

30.1. Starting a goroutine

 
 

30.2. More than one goroutine

 
 

30.3. Channels

 

30.4. Channel surfing with select

 
 
 

30.5. Blocking and deadlock

 
 

30.6. A gopher assembly line

 
 
 

Summary

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest