亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用停止通道停止 bufio.Scanner

使用停止通道停止 bufio.Scanner

Go
倚天杖 2022-05-23 17:09:55
我正在寫一些從os.Stdin使用bufio.Scanner類似的讀取行的東西:for s.scanner.Scan() {  line := s.scanner.Text()  // process line}這是在 goroutine 中運行的,我希望能夠在 achan struct{}關閉時停止它。然而,Scan直到有另一條線為止,我不知道如何阻止它,如果沒有更多的輸入,它將無限期地阻塞。誰能在這里指出我正確的方向?
查看完整描述

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

}


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號