欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用 select 切换协程

程序员文章站 2022-07-14 11:00:43
...

从不同的并发执行的协程中获取值可以使用 select 关键字来完成,它监听进入通道的数据。类型于 linux Socket IO 复用。

package main

import (
"fmt"
"time"
)

func pump1(ch chan int) {
	for i := 0; ; i++ {
		ch <- i * 2
	}
}

func pump2(ch chan int) {
	for i :=0 ; ; i++ {
		ch <- i + 5
	}
}

func suck(ch1, ch2 chan int) {
	for {
		select {
		case v := <- ch1:
			fmt.Printf("Received on channel 1: %d\n", v)
		case v := <- ch2:
			fmt.Printf("Received on channel 2: %d\n", v)
		}
	}
}

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

	go pump1(ch1)
	go pump2(ch2)
	go suck(ch1, ch2)

	time.Sleep(1e9)
}

输出

...
Received on channel 2: 45378
Received on channel 2: 45379
Received on channel 2: 45380
Received on channel 2: 45381
Received on channel 2: 45382
Received on channel 2: 45383
Received on channel 2: 45384
Received on channel 2: 45385
Received on channel 2: 45386
Received on channel 1: 87548
Received on channel 2: 45387
Received on channel 2: 45388
Received on channel 2: 45389
Received on channel 2: 45390
Received on channel 2: 45391
Received on channel 2: 45392

转载于:https://my.oschina.net/lvyi/blog/1359283