|
Ok, but that is even more simpler and shorter with plain `sync.WaitGroup`. package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
args := []int{5, 2, 4, 1, 8}
results := make([]int, len(args))
var wg sync.WaitGroup
slowSquare := func(arg int, resultIndex int) {
randomMilliseconds := rand.Intn(1000)
blockDuration := time.Duration(randomMilliseconds) * time.Millisecond
fmt.Printf("(#%d) Squaring %d, Blocking for %d milliseconds...\n", resultIndex, arg, randomMilliseconds)
<-time.After(blockDuration)
results[resultIndex] = arg * arg
fmt.Printf("(#%d) Squared %d: results[%d]=%d\n", resultIndex, arg, resultIndex, results[resultIndex])
wg.Done()
}
for i, x := range args {
wg.Add(1)
go slowSquare(x, i)
}
fmt.Println("(main) Waiting for all to finish")
wg.Wait()
fmt.Println("(main) Results: ", results)
}
(main) Waiting for all to finish
(#4) Squaring 8, Blocking for 574 milliseconds...
(#1) Squaring 2, Blocking for 998 milliseconds...
(#2) Squaring 4, Blocking for 197 milliseconds...
(#3) Squaring 1, Blocking for 542 milliseconds...
(#0) Squaring 5, Blocking for 12 milliseconds...
(#0) Squared 5: results[0]=25
(#2) Squared 4: results[2]=16
(#3) Squared 1: results[3]=1
(#4) Squared 8: results[4]=64
(#1) Squared 2: results[1]=4
(main) Results: [25 4 16 1 64]
|