如何从客户端停止goroutine?

How to stop goroutine from client?

我需要创建一个 html 页面,其中有两个按钮,一个将启动一个具有无限循环的 goroutine,另一个按钮需要打破无限循环。根据我的阅读,我了解到 goroutine 不能从外部被杀死。无论如何要实现这个?我的代码如下:

command := c.GetString("command") // from client to determine which button is clicked
quit := make(chan bool)
switch command {
    case "start":    // Button to start goroutine
        go func() {
            i := 0
            for {
                select {
                    case <- quit:
                        return
                     default:
                         fmt.Println("i: ", i)
                         i++
                         time.Sleep(3000 * time.Millisecond)
                 }
             }
         }()
     case "stop":    // Button to stop goroutine
         quit <- true
}

您的设计已经是正确的了。一个问题是您每次收到命令时都在创建新频道。这意味着无法与之前启动的 goroutine 进行通信。您需要有一个 quit 通道,该通道保持在请求之间的范围内。试试下面的东西(未经测试):

func listenForCommand() {
    var quit chan bool

    for {
        // command receiver, should fire for each command received
        command := c.GetString("command")

        switch command {
        case "start":
            if quit != nil {
                continue
            }
            quit = make(chan bool)
            go func() {
                i := 0
                for {
                    select {
                    case <-quit:
                        return
                    default:
                        fmt.Println("i: ", i)
                        i++
                        time.Sleep(3000 * time.Millisecond)
                    }
                }
            }()
        case "stop":
            if quit == nil {
                continue
            }
            quit <- true
            close(quit)
            quit = nil
        }
    }
}

您现在可以调用 listenForCommand() 开始侦听命令。此示例假定有另一个进程填充 c,因此 c.GetString("command") returns 一个命令(如果可用),或者阻塞并等待命令到达。