Golang select 通道通信选择 2

本文通过两个并发函数向两个不同的字符串通道发送数据,演示了如何使用Go语言的通道进行并发编程。通过select语句,根据通道接收数据的时间先后顺序进行判断处理,展示了Go语言中通道与goroutine的协同工作方式。

示例代码:

package main

import (
	"fmt"
	"time"
)

//定义 读写通道 函数
func chanFunc1(c chan string) {
	c <- "YDOOK.COM"
}

func chanFunc2(c chan string) {
	c <- "www.ydook.com"
}

func main() {
	c1 := make(chan string)
	c2 := make(chan string)

	go chanFunc1(c1)
	go chanFunc2(c2)

	// 根据通道返回数据的时间先后选择判断
	select {
	case ms := <-c1:
		fmt.Println("chanFunc1 actived recevied: ms = ", ms)
	case ms := <-c2:
		fmt.Println("chanFunc2 actived  recevied: ms = ", ms)
		// 设置通道不响应:延时退出
	case <-time.After(time.Second * 5):
		fmt.Println("channel is no responsed !")
	}
}

运行代码:

chanFunc1 actived recevied: ms =  YDOOK.COM


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值