如何在 Golang 中使用 goroutine 从 stdin 读取数据?

Rag*_*nar 2 concurrency go goroutine

有问题清单。我一一向用户展示问题并等待用户的回答。每个问题都应该在几秒钟内得到回答(例如问题 5 秒)。如果问题得到正确且及时的回答,那么用户将获得一些积分。我的代码看起来像:

 for i := 0; i < len(questions); i++ {
        fmt.Println(questions[i].Text)
        ans := make(chan int)
        go func() {
            fmt.Print("Enter answer ")
            var u int
            fmt.Scanf("%d\n", &u)
            ans <- u
        }()

        select {
        case userAnswer := <-ans:
            if userAnswer == questions[i].Answer {
                points++
            }
        case <-time.After(5 * time.Second):
            fmt.Println("\n Time is over!")
        }
    }
Run Code Online (Sandbox Code Playgroud)

接下来的问题是:如果用户不回答问题,那么他会收到消息“时间结束”,如预期的那样。但下一个答案将不会被处理,用户应该再次输入。它看起来像下一个输出:

question with answer  1
Enter answer: 1
1  is right answer
question with answer  2
Enter answer: 2
2  is right answer
question with answer  3
Enter answer: 
 Time is over!
question with answer  4
Enter answer: 4
4
4  is right answer
question with answer  5
Enter answer: 5
5  is right answer
Run Code Online (Sandbox Code Playgroud)

用户没有回答问题#3,因此他需要回答问题#4 两次。我知道这个问题是因为 goroutine 和通道。但我不明白,为什么不是值,它是在超时后从标准输入读取、发送到通道“ans”或从通道“ans”获取的。

为什么超时后无法正确接收来自通道的值?如何重写代码,以便用户在上一个问题超时后不需要重复输入两次?

抱歉英语不好,感谢您的帮助。

Tho*_*mas 6

这里发生的事情是,当你超时时,你仍然可以继续fmt.Scanf执行前一个 goroutine。您还在每个循环中分配一个新通道。最终结果意味着问题 3 的扫描获取您的第一个输入 4,然后尝试将其推送到永远不会被读取的通道。第二次输入 4 时,新的 goroutine 会读取它,然后将其推送到您期望找到用户输入的通道上。

相反,我建议您将用户输入卸载到为单个通道提供数据的单个 goroutine 中。

func readInput(input chan<- int) {
    for {
        var u int
        _, err := fmt.Scanf("%d\n", &u)
        if err != nil {
            panic(err)
        }
        input <- u
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样处理你的问题:

func main() {
    var points int
    userInput := make(chan int)

    go readInput(userInput)

    for i := 0; i < len(questions); i++ {
        fmt.Println(questions[i].Text)
        fmt.Print("Enter answer ")

        select {
        case userAnswer := <-userInput:
            if userAnswer == questions[i].Answer {
                fmt.Println("Correct answer:", userAnswer)
                points++
            } else {
                fmt.Println("Wrong answer")
            }
        case <-time.After(5 * time.Second):
            fmt.Println("\n Time is over!")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能想要添加一些额外的逻辑或处理来在某个时刻终止输入读取 goroutine,具体取决于程序的实际生命周期,但这是一个不同的问题。