Skip to Content
Concurrency in Go
book

Concurrency in Go

by Katherine Cox-Buday
July 2017
Intermediate to advanced
238 pages
5h 35m
English
O'Reilly Media, Inc.
Book available
Content preview from Concurrency in Go

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Up and Running with Concurrency in Go (Golang)

Up and Running with Concurrency in Go (Golang)

Stan Vangilder
Command-Line Rust

Command-Line Rust

Ken Youens-Clark

Publisher Resources

ISBN: 9781491941294Supplemental ContentErrata Page