我有一个运行几分钟的功能,我正在试图找到一种使用通道停止它的方法.
我想我不能像在下面的代码中那样做,因为我认为select
只有在default
完成之后才会处理stop
的情况.
package main
import (
"fmt"
"time"
)
func main() {
stop := make(chan int)
go func() {
for {
select {
case <-stop:
fmt.Println("return")
return
default:
fmt.Println("block")
time.Sleep(5 * time.Second) // simulate a long running function
fmt.Println("unblock")
}
}
}()
time.Sleep(1 * time.Second)
stop <- 1
}