跟着猫哥学Golang 18 - select控制并发



猫哥在实际项目中,会遇到在一个goroutine中处理多个channel的情况。

一般情况下,可以用select关键字来控制channel。golang中select可以等待/处理多个channel。对于无法识别的,还有default关键字。

看下面的例子:

package main

import (
	"fmt"
	"time"
)

func main(){
	ch1 := make(chan string)
	ch2 := make(chan string)

    go func() {
        time.Sleep(time.Second * 1)
        ch1 <- "foo"
    }()

    go func() {
        time.Sleep(time.Second * 2)
        ch2 <- "bar"
    }()

    for i := 0; i < 3; i++ {
    	time.Sleep(time.Second * i)
        select {
        case msg1 := <-ch1:
            fmt.Println("received", msg1)
        case msg2 := <-ch2:
            fmt.Println("received", msg2)
        default :
        	fmt.Println("All channels are empty...")
        }
    }
}

# 结果:
All channels are empty...
received foo
received bar


第一次上来就执行,必然是无法调度到channel的。

等待一秒后,ch1执行到;等待两秒后,ch2执行到。

如果循环继续增加,两个channel都空了,只能是后面所有的都是到default了。


你可能感兴趣的:(Go)