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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?