drxzpo70788179614 2015-01-27 10:08
浏览 81

同时选择随时发送和接收频道

Suppose I have a buffered send and unbuffered receive channel:

s := make(chan<- int, 5)
r := make(<-chan int)

Is it possible to select on them both, so that r will be selected if it has anything to read, and s will be selected if it is not full? Something equivalent to this, but not using 100% CPU:

for {
    if len(s) < cap(s) {
        // Send something
    }
    if len(r) > 0 {
        // Receive something
    }
}

Note that I want to decide what to send at the time that I send it, not earlier.

Edit

This question is basically equivalent to "Can I block until a channel is ready-to-send, without sending anything?"

  • 写回答

4条回答 默认 最新

  • dongsi5381 2015-01-27 10:14
    关注

    It's a simple select:

    select {
    case s <- n:
        // Successful send.
    case n := <- r:
        // Successful receive. Do something with n.
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题