Chapter 3. Go’s Concurrency Building Blocks

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

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:

func main() {
    go sayHello()
    // continue doing other things
}

func sayHello() {
    fmt.Println("hello")
}

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:

go func() {
    fmt.Println("hello")
}() 1
// continue doing other things

Notice that we must invoke the anonymous function immediately to use the go keyword. ...

Get Concurrency in Go 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.