go采用通道channel进行goroutine之间的通信,channel在读取时会处于阻塞状态,在某些情况并不是我们想要的效果,因此需要设置超时退出机制,可以选择select的方式,以下为实例:
package main
import (
"fmt"
"time"
"bufio"
"os"
)
func print_input(ch chan string) {
fmt.Printf("Begin to print input.\n")
for ;; {
select {
case input_ := <- ch:
fmt.Printf("get %v from standard input.\n", input_)
case <- time.After(3*time.Second): // 超时3秒没有获得数据,则退出程序,如果只是退出循环,可以return改为continue
fmt.Printf("More than 3 second no input, return\n")
return
}
}
}
func main() {
ch := make(chan string, 10)
defer close(ch)
go print_input(ch)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
in := scanner.Text()
ch <- in
if in == "EOF" {
fmt.Printf("exit\n")
return
}
}
}