【问题标题】:How to store the identifications for goroutines so that I can stop them later [duplicate]如何存储goroutines的标识,以便我以后可以停止它们[重复]
【发布时间】: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


    【解决方案1】:

    简短的回答是“你不能”。 Goroutines 不像 Unix 进程或线程。没有 PID 或线程 ID。

    您通过向主例程和 goroutine 之间共享的通道写入消息来终止 goroutine,告诉它您希望它离开而不是自己强制终止它。

    我不会复制https://blog.golang.org/pipelines的整篇文章; 你最好在那里阅读它。高点:

    • 您可以通过与 goroutine 共享通道来取消它(通常命名为 done)。您在此频道上发送的内容的实际类型并不重要。
    • 当您想发送“所有人都关闭”消息时,请关闭done 频道。这会导致通道上的任何读取立即以通道类型的零值实例成功,有效地向每个读取通道的 goroutine 广播“停止”。
    • goroutines 的核心是一个选择循环,它检查任何输入通道和done 通道上的可用输入。一旦通道关闭,done 通道已经准备好输入,goroutine 清理并退出。

    context 类型包含了这一点和许多其他细节;阅读https://blog.golang.org/context 文章将为您提供有关使用上下文控制 goroutine 的更多详细信息。


    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      相关资源
      最近更新 更多