Concurrency Basics
Wait Group
A sync.WaitGroup lets main wait until a goroutine calls Done.
Wait Group
wait_group.go
package main
import (
"fmt"
"sync"
)
func main() {
var base =
var wg sync.WaitGroup
results := make(chan int, 1)
wg.Add(1)
go func() {
defer wg.Done()
results <- base * 2
}()
wg.Wait()
value := <-results
fmt.Println("base=", base)
fmt.Println("value=", value)
fmt.Println("complete=", true)
}
package main
import (
"fmt"
"sync"
)
func main() {
var base =
var wg sync.WaitGroup
results := make(chan int, 1)
wg.Add(1)
go func() {
defer wg.Done()
results <- base * 2
}()
wg.Wait()
value := <-results
fmt.Println("base=", base)
fmt.Println("value=", value)
fmt.Println("complete=", true)
}
package main
import (
"fmt"
"sync"
)
func main() {
var base =
var wg sync.WaitGroup
results := make(chan int, 1)
wg.Add(1)
go func() {
defer wg.Done()
results <- base * 2
}()
wg.Wait()
value := <-results
fmt.Println("base=", base)
fmt.Println("value=", value)
fmt.Println("complete=", true)
}
wait group
A wait group counts active tasks so code can wait for them to finish before reading final results.