This question already has an answer here:
I am trying to create multiple goroutines and keep them running concurrently. Then when a request comes in I want to identify one of them them and stop only that particular goroutine while the rest contiue
mm := remote_method.NewPlayerCreator()
mm.NewPlayer("Leo", "Messi")
// Lets just assume that the method call starts a bot which starts playing football
mm.NewPlayer("Cristiano", "Ronaldo")
mm.StopPlayer("Leo", "Messi")
package remote_method
type PlayerCreator struct {
playerNameChannelNumberMap (map[Player](chan int))
}
type Player struct {
firstName, lastName string
}
func NewPlayerCreator() DeclaredType {
var nameChannelMap (map[Player](chan int))
m := PlayerCreator{nameChannelMap}
return m
}
func (mm NewPlayerCreator) NewPlayer(firstName string, lastName string) {
// Update the playerNameChannelNumberMap to add this new Player in the map
// Since maps are basically called by reference, the map withe the file 1 should be updated or should it ?
// Call to a goroutine that would create a new player and the player keeps on running in an infinite loop
// I can add the goroutine code in this method and not create a new method for the goroutine, if it makes more sense like this
}
func (mm NewPlayerCreator) StopPlayer(firstName string, lastName string) {
// Find the player channel in the map and send a done signal on receiving which it exits
// Remove the player entry from the map
}
What are the best known practices for doing such a thing ? TIA
</div>
The short answer is "you can't". Goroutines are not like Unix processes or threads; there's no PID or thread ID.
You terminate a goroutine by writing a message to a channel shared between the main routine and the goroutine telling it you want it to go away instead of forcibly terminating it yourself.
I won't reproduce the entire article from https://blog.golang.org/pipelines; you would be better off reading it there. High points:
done
). The actual type of what you send on this channel is unimportant.done
channel. This causes any read on the channel to immediately succeed with a zero-valued instance of the channel's type, effectively broadcasting a "stop" to every goroutine reading the channel.done
channel. Once the channel is closed, the done
channel has input ready, and the goroutine cleans up and exits.The context
type wraps this up and a number of other niceties; reading the https://blog.golang.org/context article will give you more details on using contexts to control goroutines.