←back to thread

159 points mpweiher | 7 comments | | HN request time: 0.001s | source | bottom
Show context
ricardobeat ◴[] No.43671958[source]
Strange to go all this length without mentioning the approaches that solve the problem in that first example:

1. send a close message on the channel that stops the goroutine

2. use a Context instance - `ctx.Done()` returns a channel you can select on

Both are quite easy to grasp and implement.

replies(2): >>43671984 #>>43672081 #
1. sapiogram ◴[] No.43672081[source]
You've misunderstood the example. The `scores` channel aggregates scores from all players, you can't close it just because one player leaves.

I'd really, really recommend that you try writing the code, like the post encourages. It's so much harder than it looks, which neatly sums up my overall experience with Go channels.

replies(3): >>43672616 #>>43673034 #>>43673193 #
2. politician ◴[] No.43672616[source]
It’s not entirely clear whether the author is describing a single or multiplayer game.

Among the errors in the multiplayer case is the lack of score attribution which isn’t a bug with channels as much as it’s using an int channel when you needed a struct channel.

replies(2): >>43672856 #>>43673866 #
3. jeremyjh ◴[] No.43672856[source]
The whole point is that it is multiplayer.
4. ◴[] No.43673034[source]
5. ricardobeat ◴[] No.43673193[source]
In both examples, the HandlePlayer for loop only exits if .NextScore returns an error.

In both cases, you’d need to keep track of connected players to stop the game loop and teardown the Game instance. Closing the channel during that teardown is not a hurdle.

What am I missing?

replies(1): >>43674082 #
6. ◴[] No.43673866[source]
7. guilhas ◴[] No.43674082[source]
I think nothing

I was thinking the same, the only problem is the author not keeping track of players

On HandlePlayer return err you would decrement a g.players counter, or something, and in the Game.run just do if !g.hasPlayers() break close(g.scores)

The solution requires nothing special, just basic logic that should probably be there anyway

If anything this post shows that mutexes are worse, by making bad code work