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

时间:2014-11-30 03:30:34

标签: io go nonblocking

所以我有:

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

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

1 个答案:

答案 0 :(得分:7)

一般来说,Go中没有非阻塞IO API的概念。你使用goroutines完成同样的事情。

以下是Play的示例,stdin是模拟的,因为播放不允许它。

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")
}