douchun6108 2018-05-21 19:11
浏览 42
已采纳

连续发送数据到多个通道

I have the following scenario: A function that is called every minute and each time it is called it attempts to send data to multiple defined channels as such.

var chan1 = make(chan bool)
var chan2 = make(chan bool)
var chan3 = make(chan bool)

go func() {
 for {
  <-time.After(1* time.Minute)
  chan1 <- true
  chan2 <- false
  chan3 <- true
 }
}()

Then in three separate go routines each channel is read via a select like so.

go func() {
 var myVar bool

 select {
   case <- chan1: //or chan2, chan3 etc...
     myVar = true
   default:
     myVar = false
}()

The issue is only chan1 receives the data from the first time based loop. So what appears to be occurring is the sending of data is blocked for all subsequent channels until the first channel is read. How would I correct this?

  • 写回答

1条回答 默认 最新

  • duangutian1426 2018-05-21 19:22
    关注

    Use a buffered channel:

    var chan1 = make(chan bool, 1)
    var chan2 = make(chan bool, 1)
    var chan3 = make(chan bool, 1)
    

    Or run the send asynchronously:

    go func() {
        chan1 <- true
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启