diff options
| author | Brandon C. Irizarry <brandon.irizarry@gmail.com> | 2026-04-23 16:30:12 -0400 |
|---|---|---|
| committer | Brandon C. Irizarry <brandon.irizarry@gmail.com> | 2026-04-23 16:30:12 -0400 |
| commit | 6e3c6076598eaec96afbd6624d56221c090624f6 (patch) | |
| tree | a61a2f76635ef0e6a2133812a02ea1557179bda2 | |
| parent | 074822f39b26f648ace24cd105f15c4377e1007a (diff) | |
feat: use wait group to wait for players to finish
| -rw-r--r-- | main.go | 12 |
1 files changed, 10 insertions, 2 deletions
@@ -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) } |
