【发布时间】:2014-11-25 03:42:55
【问题描述】:
我正在尝试停止执行例行程序,但找不到实现此目的的方法。我正在考虑使用第二个频道,但如果我从中读取它会阻止它不是吗?这是一些我希望能解释我想要做什么的代码。
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")
}
【问题讨论】:
标签: go