by teraflop · 2y ago · 0 comments
The desired behavior is that printing the first result should only wait for the first result to be available, not for all the results to be available.
package main
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
)
func main() {
args := []int{5, 2, 4, 1, 8}
var indexGen atomic.Int32
indexGen.Store(-1)
results := make([]int, len(args))
finished := make(chan bool)
slowSquare := func(arg int, index int) {
randomMilliseconds := rand.Intn(1000)
blockDuration := time.Duration(randomMilliseconds) * time.Millisecond
fmt.Printf("Squaring %d, Blocking for %d milliseconds...\n", arg, randomMilliseconds)
<-time.After(blockDuration)
idx := indexGen.Add(1)
results[idx] = arg * arg
fmt.Printf("Squared %d: results[%d]=%d\n", arg, idx, results[idx])
finished <- true
}
prettyPrinter := func() {
for range time.NewTicker(time.Second).C {
fmt.Println("Results: ", results)
}
}
go prettyPrinter()
for idx, x := range args {
go slowSquare(x, idx)
}
<-finished
fmt.Println("First Result: ", results[0])
fmt.Println("So-far Results: ", results)
}This will also print some results multiple times. I think Chris wants to print each result once.
You can simply comment out the println and just pick the first results[0]. Again, the repeated println for all results was only added for demonstrative clarity.
Frankly, the above satisfies all primary goals. The rest is just nitpicking - without a formal specification of the problem one can argue all day.
I wasn't talking about the random wait at all. I was talking about
for range time.NewTicker(time.Second).C {
fmt.Println("Results: ", results)
}
>You can simply comment out the println and just pick the first results[0].When should we look at results[0]? There needs to be some notification that results[0] is ready to be looked at. Similarly with all the rest of the results.
>Frankly, the above satisfies all primary goals. The rest is just nitpicking - without a formal specification of the problem one can argue all day.
I guess we have to disagree. From my reading of the blog post it was pretty clear what Chris wanted, and the code you provided didn't meet that.