From 431bafa41ae1a4b97b04a43fc491080497229340 Mon Sep 17 00:00:00 2001 From: "Brandon C. Irizarry" Date: Thu, 23 Apr 2026 17:23:20 -0400 Subject: refactor: move termination task into separate function This is the stopGame function. --- main.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index c9a220c..ee0d77e 100644 --- a/main.go +++ b/main.go @@ -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) +} -- cgit v1.2.3