如何存储goroutine的标识,以便我以后可以阻止它们
我试图创建多个goroutine并使它们同时运行。然后,当一个请求进来时,我想识别其中一个,并且只停止那个特定的goroutine,而其余的继续 文件1 文件2 做这样一件事的最佳实践是什么?如何存储goroutine的标识,以便我以后可以阻止它们,go,Go,我试图创建多个goroutine并使它们同时运行。然后,当一个请求进来时,我想识别其中一个,并且只停止那个特定的goroutine,而其余的继续 文件1 文件2 做这样一件事的最佳实践是什么? TIA简而言之,你不能。goroutine不像Unix进程或线程;没有PID或线程ID 通过向主例程和goroutine之间共享的通道写入消息,告诉goroutine您希望它消失,而不是自己强制终止,从而终止goroutine 我不会从中复制整篇文章; 你最好在那里读。要点: 您可以通过与goroutin
TIA简而言之,你不能。goroutine不像Unix进程或线程;没有PID或线程ID 通过向主例程和goroutine之间共享的通道写入消息,告诉goroutine您希望它消失,而不是自己强制终止,从而终止goroutine 我不会从中复制整篇文章; 你最好在那里读。要点: 您可以通过与goroutine共享一个通常名为done的频道来取消goroutine。你在这个频道上发送的内容的实际类型并不重要。 当您想要发送“所有人关闭”消息时,请关闭“完成”频道。这会导致通道上的任何读取立即成功,通道类型的零值实例,有效地向读取通道的每个goroutine广播一个stop。 goroutine的核心是一个select循环,它检查任何输入通道和done通道上的可用输入。一旦通道关闭,完成的通道已准备好输入,goroutine将清理并退出。 上下文类型包含了这一点和其他一些细节;阅读本文将为您提供有关使用上下文控制goroutine的更多详细信息
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
}