1 回答
TA贡献1796条经验 获得超7个赞
通过再创建一个间接并忽略底层,我们可以停止。
// actual reading, converts input stream to a channel
func readUnderlying(lines chan interface{}) {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
lines <- s.Text()
}
lines <- s.Err()
}
func read(stop chan struct{}) {
input := make(chan interface{}) // input stream
go readUnderlying(input) // go and read
for {
select { // read or close
case lineOrErr := <-input:
fmt.Println(lineOrErr)
case <-stop:
return
}
}
}
func main() {
stop := make(chan struct{})
go read(stop)
// wait some to simulate blocking
time.Sleep(time.Second * 20) // it will print what is given
close(stop)
time.Sleep(time.Second * 20) // stopped so no more processing
}
- 1 回答
- 0 关注
- 151 浏览
添加回答
举报