Go
Beginner
1 min read
Starting Goroutines
Example
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // signal completion when function returns
fmt.Printf("Worker %d starting\n", id)
// Simulate work with a sleep
time.Sleep(time.Duration(id) * 100 * time.Millisecond)
fmt.Printf("Worker %d done\n", id)
}
func main() {
const numWorkers = 5
var wg sync.WaitGroup
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, &wg) // launch goroutine
}
fmt.Println("All workers launched, waiting...")
wg.Wait() // block until all workers call wg.Done()
fmt.Println("All workers finished")
// Anonymous goroutine
done := make(chan struct{})
go func() {
defer close(done)
fmt.Println("Anonymous goroutine running")
}()
<-done // wait for the anonymous goroutine
}