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
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了