Go Goroutines
Concurrent programming with goroutines
Basic Goroutine
func sayHello() { # define function
fmt.Println("Hello")
}
go sayHello() # run as goroutine
go func() { # anonymous goroutine
fmt.Println("World")
}()
WaitGroup
import "sync" # import sync package
var wg sync.WaitGroup # create WaitGroup
wg.Add(1) # add one goroutine to wait for
go func() {
defer wg.Done() # mark as done when finished
// code
}()
wg.Wait() # wait for all goroutines
Multiple Goroutines
for i := 0; i < 5; i++ { # spawn 5 goroutines
wg.Add(1)
go func(id int) { # pass value to avoid closure issues
defer wg.Done()
fmt.Println("Goroutine", id)
}(i)
}
wg.Wait()
Mutex for Synchronization
var mu sync.Mutex # create mutex
var counter = 0
mu.Lock() # acquire lock
counter++ # safe to modify
mu.Unlock() # release lock