Golang中将os.stdin作为Goroutines中的Reader使用

huangapple go评论84阅读模式
英文:

Golang os.stdin as a Reader in Goroutines

问题

在Goroutine中使用os.Stdin作为Reader是否可以?基本上,我想要实现的是在不阻塞主线程的情况下,让用户输入一条消息。

示例:

go func() {
    for {
        consolereader := bufio.NewReader(os.Stdin)

        input, err := consolereader.ReadString('\n') // 这将提示用户输入

        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }

        fmt.Println(input)
    }
}()
英文:

Is it okay to use os.stdin as a Reader in a Goroutine? Basically what I would like to accomplish is to enable the user to enter a message without blocking the main thread.

Example:

go func() {
	for {
		consolereader := bufio.NewReader(os.Stdin)

		input, err := consolereader.ReadString('\n') // this will prompt the user for input

		if err != nil {
		     fmt.Println(err)
		     os.Exit(1)
		}

		fmt.Println(input)
	}
}()

答案1

得分: 2

是的,这是完全可以的。只要这是唯一与os.Stdin交互的goroutine,一切都会正常工作。

顺便说一下,你可能想使用bufio.Scanner - 它比bufio.Reader更好用:

go func() {
    consolescanner := bufio.NewScanner(os.Stdin)

    // 默认情况下,bufio.Scanner会扫描以换行符分隔的行
    for consolescanner.Scan() {
        input := consolescanner.Text()
        fmt.Println(input)
    }

    // 在最后检查一次是否遇到了任何错误
    // (一旦遇到错误,Scan()方法将立即返回false)
    if err := consolescanner.Err(); err != nil {
         fmt.Println(err)
         os.Exit(1)
    }
}()
英文:

Yes, this is perfectly fine. So long as this is the only goroutine that is interacting with os.Stdin, everything will work properly.

By the way, you may want to use bufio.Scanner - it's a bit nicer to work with than bufio.Reader:

go func() {
    consolescanner := bufio.NewScanner(os.Stdin)

    // by default, bufio.Scanner scans newline-separated lines
    for consolescanner.Scan() {
        input := consolescanner.Text()
        fmt.Println(input)
    }

    // check once at the end to see if any errors
    // were encountered (the Scan() method will
    // return false as soon as an error is encountered) 
    if err := consolescanner.Err(); err != nil {
         fmt.Println(err)
         os.Exit(1)
    }
}()

huangapple
  • 本文由 发表于 2015年11月18日 04:21:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/33766251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定