Go语言笔记

Apr 9, 2019


Select

Go里面的Select和Java Nio里面的模式有点类似,就是一个线程(进程/协程)同时去监听多个目标的状态。在Go里面,Select可以让一个Goroutine同时去监听多个Channel是否到达准备状态,例子如下:

	timeOut := make(chan bool, 1)
	go func() {
		time.Sleep(time.Duration(time.Second * 5))
		timeOut <- true
	}()
	timeOutNext := make(chan bool, 1)
	go func() {
		time.Sleep(time.Duration(time.Second * 10))
		timeOutNext <- true
	}()
	select {
	case <-timeOut:
		fmt.Println("TimeOut After 5 Seconds!")
	case <-timeOutNext:
		fmt.Println("TimeOut After 10 Seconds!")
	}

上面代码执行时,Select阻塞到timeOut这个Channel收到输入时就退出了,要让Select不退出,timeOutNext这个Channel也有机会收到输入时,需要像下面这样写:

	timeOut := make(chan bool, 1)
	go func() {
		time.Sleep(time.Duration(time.Second * 5))
		timeOut <- true
	}()
	timeOutNext := make(chan bool, 1)
	go func() {
		time.Sleep(time.Duration(time.Second * 10))
		timeOutNext <- true
	}()
	for {
		select {
		case <-timeOut:
			fmt.Println("TimeOut After 5 Seconds!")
		case <-timeOutNext:
			fmt.Println("TimeOut After 10 Seconds!")
		}
	}

上一篇博客:RabbitMQ 介绍
下一篇博客:流媒体知识整理