GO语言笔记--(五)从阻塞的通道channel中退出

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


版权声明:本文为lccever原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。