henryspace

记录精彩的程序人生 开始使用

Part 23 - Go 语言学习 - select 调度

go select运用

package main

import (
	"fmt"
	"math/rand"
	"time"
)

// 随机生成数字
func generator() chan int{
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(
				time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}

func main() {
    // c1, c2 接收channel的值
	var c1, c2 = generator(), generator()
	for {
		select { // 非阻塞
		case n := <-c1:
			fmt.Println("received c1:", n)
		case n := <-c2:
			fmt.Println("received c2:", n)
		}
		// 这里不用default,因为在生成数字的等待期,default会一直执行
	}
结果
received c1: 0
received c2: 0
received c2: 1
received c1: 1
received c1: 2
received c2: 2
received c1: 3
received c2: 3
received c2: 4
received c2: 5
received c1: 4
received c1: 5
received c1: 6
received c2: 6
received c1: 7
received c2: 7
received c1: 8
received c1: 9
received c2: 8
received c1: 10
received c2: 9
received c1: 11
received c2: 10
received c2: 11
received c1: 12
received c1: 13
received c1: 14
received c2: 12
received c2: 13
received c2: 14
received c2: 15
received c1: 15
received c2: 16
received c2: 17
received c1: 16
received c2: 18
received c1: 17
received c2: 19
received c1: 18
received c2: 20
...




}

评论
留下你的脚步