【发布时间】:2016-08-01 14:29:14
【问题描述】:
我需要创建一个 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在运行?
-
@ain 不,不会有多个 goroutines...
-
@Jsor 停止不起作用。即使按下停止按钮,循环仍在继续..
-
无关,在你的“停止”情况下关闭退出(
close(quit))就像通过它发送消息一样容易,并且关闭不会阻塞(虽然它 如果您尝试多次这样做,将会恐慌)。我通常使用 close,因为它可以在单个操作中终止多个侦听例程,而不必向每个例程发送消息。