英文:
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)
}
}()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论