【发布时间】:2019-08-17 11:16:15
【问题描述】:
我正在尝试创建多个 goroutine 并让它们同时运行。然后,当有请求进来时,我想识别其中一个,并只停止那个特定的 goroutine,而其余的继续
文件 1
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")
文件 2
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
}
做这种事情的最佳实践是什么? TIA
【问题讨论】:
标签: go