我試圖阻止一個去程序,但我找不到一種方法來實現這一點。我正在考慮使用第二頻道,但如果我從中讀到它會阻止它,不是嗎?這裏有一些代碼,我希望解釋我想要做的事情。如何通知goroutine停止運行?
package main
import "fmt"
import "time"
func main() {
var tooLate bool
proCh := make(chan string)
go func() {
for {
fmt.Println("working")
//if is tooLate we stop/return it
if tooLate {
fmt.Println("stopped")
return
}
//processing some data and send the result on proCh
time.Sleep(2 * time.Second)
proCh <- "processed"
fmt.Println("done here")
}
}()
select {
case proc := <-proCh:
fmt.Println(proc)
case <-time.After(1 * time.Second):
// somehow send tooLate <- true
//so that we can stop the go routine running
fmt.Println("too late")
}
time.Sleep(4 * time.Second)
fmt.Println("finish\n")
}
http:// s的可能重複tackoverflow.com/questions/6807590/how-to-stop-a-goroutine – jimt 2014-09-30 14:01:34