Goroutines Intro

View saved

Start a goroutine

Prefix a function call with go to run it concurrently.

package main

import (
	"fmt"
	"time"
)

func main() {
	go fmt.Println("in a goroutine")
	time.Sleep(10 * time.Millisecond)
	fmt.Println("main")
}

Main exits early

When main returns, the program ends—even if other goroutines are still running. Coordinate with channels or WaitGroup.

Use WaitGroup for practice

A wait group waits until worker goroutines finish.

var wg sync.WaitGroup
wg.Add(1)
go func() {
	defer wg.Done()
	fmt.Println("work")
}()
wg.Wait()

Concurrency caution

  • Goroutines are cheap, but shared data needs synchronization
  • Prefer communicating over channels when learning
  • Do not add sleeps as real synchronization in production
  • Start with clear sequential code, then add concurrency

Comments

One comment per signed-in account. Comments are saved with this page’s URL.