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 關注
- 175 瀏覽
添加回答
舉報