1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
通過再創(chuàng)建一個(gè)間接并忽略底層,我們可以停止。
// 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 關(guān)注
- 178 瀏覽
添加回答
舉報(bào)