Goroutines

A goroutine is a lightweight thread managed by the Go runtime.

  1. go f(x, y, z)

starts a new goroutine running

  1. f(x, y, z)

The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.

Goroutines run in the same address space, so access to shared memory must be synchronized. The sync package provides useful primitives, although you won't need them much in Go as there are other primitives. (See the next slide.)

goroutines.go

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func say(s string) {
  7. for i := 0; i < 5; i++ {
  8. time.Sleep(100 * time.Millisecond)
  9. fmt.Println(s)
  10. }
  11. }
  12. func main() {
  13. go say("world")
  14. say("hello")
  15. }