使用停止通道停止 bufio.Scanner

我正在写一些从os.Stdin使用bufio.Scanner类似的读取行的东西:


for s.scanner.Scan() {

  line := s.scanner.Text()

  // process line

}

这是在 goroutine 中运行的,我希望能够在 achan struct{}关闭时停止它。然而,Scan直到有另一条线为止,我不知道如何阻止它,如果没有更多的输入,它将无限期地阻塞。


谁能在这里指出我正确的方向?


倚天杖
浏览 152回答 1
1回答

芜湖不芜

通过再创建一个间接并忽略底层,我们可以停止。// actual reading, converts input stream to a channelfunc readUnderlying(lines chan interface{}) {&nbsp; &nbsp; s := bufio.NewScanner(os.Stdin)&nbsp; &nbsp; for s.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; lines <- s.Text()&nbsp; &nbsp; }&nbsp; &nbsp; lines <- s.Err()}func read(stop chan struct{}) {&nbsp; &nbsp; input := make(chan interface{}) // input stream&nbsp; &nbsp; go readUnderlying(input) // go and read&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select { // read or close&nbsp; &nbsp; &nbsp; &nbsp; case lineOrErr := <-input:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(lineOrErr)&nbsp; &nbsp; &nbsp; &nbsp; case <-stop:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; stop := make(chan struct{})&nbsp; &nbsp; go read(stop)&nbsp; &nbsp; // wait some to simulate blocking&nbsp; &nbsp; time.Sleep(time.Second * 20) // it will print what is given&nbsp; &nbsp; close(stop)&nbsp; &nbsp; time.Sleep(time.Second * 20) // stopped so no more processing}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go