|
You can completely ignore that pretty print function as it not essential to the goal. Revised example without pretty-print at https://go.dev/play/p/LkAT_g95BLO As soon as you have completed `<-finished` in the main go-routine, it means `results[0]` has been populated and is ready for read. If you want to wait till all results are available, then perform `<-finished`, `len(results)` times. (Or use sync.WaitGroup) package main
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
)
func main() {
args := []int{5, 2, 4, 1, 8}
var resultCount atomic.Int32
resultCount.Store(-1)
results := make([]int, len(args))
finished := make(chan bool, len(args))
slowSquare := func(arg int, fnNum int) {
randomMilliseconds := rand.Intn(1000)
blockDuration := time.Duration(randomMilliseconds) * time.Millisecond
fmt.Printf("(#%d) Squaring %d, Blocking for %d milliseconds...\n", fnNum, arg, randomMilliseconds)
<-time.After(blockDuration)
resultIndex := resultCount.Add(1)
results[resultIndex] = arg * arg
fmt.Printf("(#%d) Squared %d: results[%d]=%d\n", fnNum, arg, resultIndex, results[resultIndex])
finished <- true
}
for i, x := range args {
go slowSquare(x, i)
}
fmt.Println("(main) Waiting for first finish")
<-finished
fmt.Println("(main) First Result: ", results[0])
}
|