9. Goroutines

Goroutines are the basic primitive for concurrency in Go and are very easy to create. Go is intended for a world in which the number of available cores keeps increasing, so it encourages a concurrent programming style. The easy creation of goroutines is a key part of that.

Creating Goroutines

 6  go fmt.Printf("Printed in the background\n") 7  i := 1 8  go fmt.Printf("Currently, i is %d\n", i) 9  go func() {10    fmt.Printf("i: %d\n", i)11  }()12  i++13  time.Sleep(1000000000)

From: goroutine.go

You create a new goroutine by prefixing any function call with the keyword go. This creates a new goroutine containing the call frame and schedules it to run.

The newly created goroutine behaves like a thread ...

Get The Go Programming Language Phrasebook 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.