golang select 选择器的两种方案

golang select 选择器



常规模式:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var chs1 = make(chan int)
	var chs2 = make(chan float64)
	var chs3 = make(chan string)
	var ch4close = make(chan int)
	defer close(ch4close)

	go func(c chan int,ch4close chan int) {
		for i := 0; i < 5; i++ {
			c <- i
		}
		close(c)
		ch4close <- 1
	}(chs1,ch4close)

	go func(c chan float64,ch4close chan int) {
		for i := 0; i < 5; i++ {
			c <- float64(i) + 0.1
		}
		close(c)
		ch4close <- 1
	}(chs2,ch4close)

	go func(c chan string,ch4close chan int) {
		for i := 0; i < 5; i++ {
			c <- "string:" + strconv.Itoa(i)
		}
		close(c)
		ch4close <- 1
	}(chs3,ch4close)

	done := 0
	finished := 0
	for finished < 3 {
		select {
		case v,ok := <-chs1:
			if ok {
				done = done + 1
				fmt.Println(0,v)
			}
		case v,ok := <-chs2:
			if ok {
				done = done + 1
				fmt.Println(1,ok := <-chs3:
			if ok {
				done = done + 1
				fmt.Println(2,v)
			}
		case _,ok := <- ch4close:
			if ok {
				finished = finished+1
			}
		}
	}
	fmt.Println("Done",done)
}


reflect设计


package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var chs1 = make(chan int)
	var chs2 = make(chan float64)
	var chs3 = make(chan string)
	var ch4close = make(chan int)
	defer close(ch4close)

	go func(c chan int,ch4close)


	var selectCase = make([]reflect.SelectCase,4)
	selectCase[0].Dir = reflect.SelectRecv
	selectCase[0].Chan = reflect.ValueOf(chs1)

	selectCase[1].Dir = reflect.SelectRecv
	selectCase[1].Chan = reflect.ValueOf(chs2)

	selectCase[2].Dir = reflect.SelectRecv
	selectCase[2].Chan = reflect.ValueOf(chs3)

	selectCase[3].Dir = reflect.SelectRecv
	selectCase[3].Chan = reflect.ValueOf(ch4close)

	done := 0
	finished := 0
	for finished < len(selectCase)-1 {
		chosen,recv,recvOk := reflect.Select(selectCase)

		if recvOk {
			done = done+1
			switch chosen {
			case 0:
				fmt.Println(chosen,recv.Int())
			case 1:
				fmt.Println(chosen,recv.Float())
			case 2:
				fmt.Println(chosen,recv.String())
			case 3:
				finished = finished+1
				done = done-1
				// fmt.Println("finished\t",finished)
			}
		}
	}
	fmt.Println("Done",done)

}

相关文章

程序目录结构 简单实现,用户登录后返回一个jwt的token,下次请求带上token请求用户信息接口并返回信息...
本篇博客的主要内容是用go写一个简单的Proof-of-Work共识机制,不涉及到网络通信环节,只是一个本地的简...
简介 默克尔树(MerkleTree)是一种典型的二叉树结构,其主要特点为: 最下面的叶节点包含存储数据或其...
接下来学习并发编程, 并发编程是go语言最有特色的地方, go对并发编程是原生支持. goroutine是go中最近本...
先普及一下, 什么是广度优先搜索 广度优先搜索类似于树的层次遍历。从图中的某一顶点出发,遍历每一个顶...
第一天: 接口的定义和实现 第二天: 一. go语言是面向接口编程. 在学习继承的时候说过, go语言只有封装,...