Goroutines

go starts a function concurrently. It is not an operating-system thread, and it is not background magic that waits for the end by itself.

go f() starts f in a new goroutine and goes on immediately. A goroutine is cheaper than an OS thread: the runtime keeps them on a small number of system threads and switches when a goroutine blocks on a channel, the network, or a system call.

The main beginner's mistake is not waiting for the work:

func main() {
    go func() {
        fmt.Print("go")
    }()
}

main can finish before the goroutine has time to print the text. The return of main kills the process together with every goroutine. "It prints on my machine" proves nothing.

The second mistake is a shared variable. Two goroutines that write n++ without synchronization create a race. A channel or a mutex decides who owns the value. While there is one owner, synchronization is not needed: a goroutine can calmly build its local result and send it outward as one value.

Do not create a goroutine for every sneeze inside a library. A library function that silently does go hides the lifetime. The caller does not know whom to wait for or how to cancel. The goroutine is started by whoever owns the request: the handler, main, a pool. Everyone else accepts a context and ordinary functions.

A goroutine leak is a goroutine waiting on a channel nobody will write to, or a ticker that was not stopped. The process is alive, memory grows, and there is no error stack. In review, look for a pair for every go: where this goroutine is guaranteed to finish.

Practice

  1. The end of main

    What happens to goroutines when the function main has returned?

    • The runtime waits for every goroutine
    • The process exits, and the goroutines stop with it
    • The goroutines move to a background process
    • The compiler forbids go inside main
  2. Who starts go

    Where is it most appropriate to start a goroutine, if a library function simply computes data?

    • Inside the library, hidden, so the API is shorter
    • At the boundary that is responsible for the lifetime of the work
    • In the package init
    • In every getter of the struct
  3. A sign of a leak

    A goroutine is blocked reading a channel that nobody will send another value on and that will not be closed. Will it finish by itself? Write yes or no.