WeCodeAcademy

Go Goroutines and Channels

A goroutine is a lightweight task started with go. Channels pass values safely between goroutines. A WaitGroup waits for goroutines to finish.

ExampleGo
package main

import (
  "fmt"
  "sync"
)

func main() {
  ch := make(chan int)
  go func() {
    for i := 1; i <= 3; i++ {
      ch <- i * i
    }
    close(ch)
  }()
  for v := range ch {
    fmt.Println("received", v)
  }

  var wg sync.WaitGroup
  var mu sync.Mutex
  total := 0
  for i := 1; i <= 10; i++ {
    wg.Add(1)
    go func(n int) {
      defer wg.Done()
      mu.Lock()
      total += n
      mu.Unlock()
    }(i)
  }
  wg.Wait()
  fmt.Println("total", total)
}
Output
received 1
received 4
received 9
total 55

The mutex protects total so that goroutines running at the same time do not corrupt it. This is what makes Go popular for servers.

Quick check

Which keyword starts a goroutine?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.