In this chapter, we’ll discuss Go’s rich tapestry of features that support its concurrency story. By the end of this chapter, you should have a good understanding of the syntax, functions, and packages available to you, and their functionality.
Goroutines are one of the most basic units of organization in a Go program, so it’s important we understand what they are and how they work. In fact, every Go program has at least one goroutine: the main goroutine, which is automatically created and started when the process begins. In almost any program you’ll probably find yourself reaching for a goroutine sooner or later to assist in solving your problems. So what are they?
Put very simply, a goroutine is a function that is running concurrently (remember: not necessarily in parallel!) alongside other code. You can start one simply by placing the
go keyword before a function:
// continue doing other things
Anonymous functions work too! Here’s an example that does the same thing as the previous example; however, instead of creating a goroutine from a function, we create a goroutine from an anonymous function:
Notice that we must invoke the anonymous function immediately to use the
go keyword. ...