Go中的Channel——range和select

数据接受者总是面临这样的问题:何时停止等待数据?还会有更多的数据么,还是所有内容都完成了?我应该继续等待还是该做别的了?

对于该问题,一个可选的方式是,持续的访问数据源并检查channel是否已经关闭,但是这并不是高效的解决方式。Go提供了range关键字,将其使用在channel上时,会自动等待channel的动作一直到channel被关闭

 
  1. 示例代码1

  2. package main

  3. import (

  4. "fmt"

  5. "time"

  6. "strconv"

  7. )

  8.  
  9. func makeCakeAndSend(cs chan string, count int) {

  10. for i := 1; i <= count; i++ {

  11. cakeName := "Strawberry Cake " + strconv.Itoa(i)

  12. cs <- cakeName //send a strawberry cake

  13. }

  14. }

  15.  
  16. func receiveCakeAndPack(cs chan string) {

  17. for s := range cs {

  18. fmt.Println("Packing received cake: ", s)

  19. }

  20. }

  21.  
  22. func main() {

  23. cs := make(chan string)

  24. go makeCakeAndSend(cs, 5)

  25. go receiveCakeAndPack(cs)

  26.  
  27. //sleep for a while so that the program doesn’t exit immediately

  28. time.Sleep(3 * 1e9)

  29. }

 
  1. 输出结果

  2. Packing received cake: Strawberry Cake 1

  3. Packing received cake: Strawberry Cake 2

  4. Packing received cake: Strawberry Cake 3

  5. Packing received cake: Strawberry Cake 4

  6. Packing received cake: Strawberry Cake 5

我们告诉了蛋糕制作器我们需要5个蛋糕,但是蛋糕装箱器并不知道数目,而在之前版本的代码中,我们写死了具体的接收数目。上面的代码中,通过对channel使用range关键字,我们避免了给接收者写明要接收的数据个数这种不合理的需求——当channel被关闭时,接收者的for循环也被自动停止了

Channel and select

select关键字用于多个channel的结合,这些channel会通过类似于are-you-ready polling的机制来工作。select中会有case代码块,用于发送或接收数据——不论通过<-</

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

isevena、

谢谢您的肯定

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值