我试图阻止一个去程序,但我找不到一种方法来实现这一点。我正在考虑使用第二频道,但如果我从中读到它会阻止它,不是吗?这里有一些代码,我希望解释我想要做的事情。如何通知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