From 6e3c6076598eaec96afbd6624d56221c090624f6 Mon Sep 17 00:00:00 2001 From: "Brandon C. Irizarry" Date: Thu, 23 Apr 2026 16:30:12 -0400 Subject: feat: use wait group to wait for players to finish --- main.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index f561be4..663e6aa 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "math/rand" + "sync" "time" ) @@ -42,12 +43,13 @@ func game(numPlayers, faces int) { // player took to hit the winning number. scores := make(chan Score) + var wg sync.WaitGroup for i := range numPlayers { id := i + 1 fmt.Printf("Player %d start!\n", id) // Spawn a player. - go func() { + wg.Go(func() { var score int // Start rolling the dice! @@ -58,13 +60,19 @@ func game(numPlayers, faces int) { if outcome == winningNumber { scores <- Score{id: id, score: score} + return } time.Sleep(1 * time.Second) } - }() + }) } + go func() { + wg.Wait() + close(scores) + }() + for score := range scores { fmt.Printf("%v\n", score) } -- cgit v1.2.3