Golang学习笔记-管道chan的使用

多个管道中获取数据

package main

import (
	"fmt"
	"time"
)

//管道 channel,向管道发送数据
func send_channel(ch chan int, begin int){
    
    
	for i := begin; i < begin+10; i++{
    
    
		ch <- i 	//向管道发送数据
	}
}


func main(){
    
    
	fmt.Printf("Main running...\n")
	channelV1 := make(chan int)
	channelV2 := make(chan int)

	go send_channel(channelV1, 0)
	go send_channel(channelV2, 10)

	time.Sleep(time.Second)

	for{
    
    
		select {
    
    
		case val := <-channelV1: //接收管道的数据
			fmt.Printf("get value %d from channel_v1.\n",val)

		case val := <-channelV2:
			fmt.Printf("get value %d from channel_v2.\n",val)

		case <-time.After(2*time.Second):
			fmt.Printf("Time out.")
			return
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_40904479/article/details/106481888