diff options
| author | Brandon C. Irizarry <brandon.irizarry@gmail.com> | 2026-04-23 17:23:20 -0400 |
|---|---|---|
| committer | Brandon C. Irizarry <brandon.irizarry@gmail.com> | 2026-04-23 17:23:20 -0400 |
| commit | 431bafa41ae1a4b97b04a43fc491080497229340 (patch) | |
| tree | 315f0b792a596e9b2519695f108399403e784ad4 | |
| parent | 6467dc587095769cca93719429ebba2cf2329954 (diff) | |
refactor: move termination task into separate function
This is the stopGame function.
| -rw-r--r-- | main.go | 20 |
1 files changed, 14 insertions, 6 deletions
@@ -44,12 +44,12 @@ func game(numPlayers, faces int) { // player took to hit the winning number. finishedPlayers := make(chan Player) - var wg sync.WaitGroup + var guild sync.WaitGroup for i := range numPlayers { id := i + 1 // Spawn a player. - wg.Go(func() { + guild.Go(func() { var score int // Start rolling the dice! @@ -69,13 +69,14 @@ func game(numPlayers, faces int) { }) } - go func() { - wg.Wait() - close(finishedPlayers) - }() + // Launch a non-blocking daemon to wait for the guild to + // finish, so that we can close the finishedPlayers channel. + go stopGame(&guild, finishedPlayers) minPlayer := Player{score: math.MaxInt} + // The range loop waits for [Player] score reports from the + // workers (or else a [stopGame] request.) for player := range finishedPlayers { if player.score < minPlayer.score { minPlayer = player @@ -89,3 +90,10 @@ func game(numPlayers, faces int) { func throwDie(faces int) int { return rand.Intn(faces) + 1 } + +// stopGame waits for the members of the guild to finish, and then +// closes source for use. It functions as a "termination task." +func stopGame(guild *sync.WaitGroup, source chan Player) { + guild.Wait() + close(source) +} |
