如何使用Go以非阻塞方式从控制台读取输入?

mar*_*cio 4 io nonblocking go

所以我有:

import (
    "bufio"
    "os"
)
//...
var reader = bufio.NewReader(os.Stdin)
str, err := reader.ReadString('\n')
Run Code Online (Sandbox Code Playgroud)

reader.ReadString('\n')阻止执行.我想以非阻塞方式读取输入.是否可以通过os.Stdin使用bufio包或Go中的任何其他std lib包来实现非阻塞缓冲输入?

Dav*_*rth 9

通常,Go中没有非阻塞IO API的概念.你使用goroutines完成同样的事情.

这是Play上的一个例子,stdin是模拟的,因为play不允许它.

package main

import "fmt"
import "time"

func main() {
    ch := make(chan string)
    go func(ch chan string) {
        /* Uncomment this block to actually read from stdin
        reader := bufio.NewReader(os.Stdin)
        for {
            s, err := reader.ReadString('\n')
            if err != nil { // Maybe log non io.EOF errors, if you want
                close(ch)
                return
            }
            ch <- s
        }
        */
        // Simulating stdin
        ch <- "A line of text"
        close(ch)
    }(ch)

stdinloop:
    for {
        select {
        case stdin, ok := <-ch:
            if !ok {
                break stdinloop
            } else {
                fmt.Println("Read input from stdin:", stdin)
            }
        case <-time.After(1 * time.Second):
            // Do something when there is nothing read from stdin
        }
    }
    fmt.Println("Done, stdin must be closed")
}
Run Code Online (Sandbox Code Playgroud)