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

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

Golang os.stdin as a Reader in Goroutines

问题

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

示例:

  1. go func() {
  2. for {
  3. consolereader := bufio.NewReader(os.Stdin)
  4. input, err := consolereader.ReadString('\n') // 这将提示用户输入
  5. if err != nil {
  6. fmt.Println(err)
  7. os.Exit(1)
  8. }
  9. fmt.Println(input)
  10. }
  11. }()
英文:

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:

  1. go func() {
  2. for {
  3. consolereader := bufio.NewReader(os.Stdin)
  4. input, err := consolereader.ReadString('\n') // this will prompt the user for input
  5. if err != nil {
  6. fmt.Println(err)
  7. os.Exit(1)
  8. }
  9. fmt.Println(input)
  10. }
  11. }()

答案1

得分: 2

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

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

  1. go func() {
  2. consolescanner := bufio.NewScanner(os.Stdin)
  3. // 默认情况下,bufio.Scanner会扫描以换行符分隔的行
  4. for consolescanner.Scan() {
  5. input := consolescanner.Text()
  6. fmt.Println(input)
  7. }
  8. // 在最后检查一次是否遇到了任何错误
  9. // (一旦遇到错误,Scan()方法将立即返回false)
  10. if err := consolescanner.Err(); err != nil {
  11. fmt.Println(err)
  12. os.Exit(1)
  13. }
  14. }()
英文:

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:

  1. go func() {
  2. consolescanner := bufio.NewScanner(os.Stdin)
  3. // by default, bufio.Scanner scans newline-separated lines
  4. for consolescanner.Scan() {
  5. input := consolescanner.Text()
  6. fmt.Println(input)
  7. }
  8. // check once at the end to see if any errors
  9. // were encountered (the Scan() method will
  10. // return false as soon as an error is encountered)
  11. if err := consolescanner.Err(); err != nil {
  12. fmt.Println(err)
  13. os.Exit(1)
  14. }
  15. }()

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:

确定