我需要創建一個有兩個按鈕的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
}
這幾乎是標準的做法,是的,你有任何具體的問題嗎? – LinearZoetrope
是否允許多次按「開始」按鈕,即可能有多個goroutine正在運行? – ain
@ain不會有多個門廳... –