dongzhizhai4070 2016-12-13 21:47 采纳率: 0%
浏览 33

Golang的垃圾通道?

I accept a done channel in my function, which is nice for notifying callers when some async process has finished, if they care. This is very useful for writing unit tests for example.

If my caller doesn't need this functionality, is there an idiomatic way to pass a garbage channel, where all values sent to it are discarded immediately? I was initially surprised sending nil didn't work (sending to nil blocks the sender). I can think of one gross implementation (like a goroutine always running that consumes from this channel), but I would love to write something like:

func myFunc(foo int, done chan bool) {
    ....
}

func main() {
    myfunc(4, _)
}

Is there a simple way to accomplish this?

  • 写回答

2条回答 默认 最新

  • doswy02440 2016-12-13 21:57
    关注

    You can use a select on the send to avoid blocking:

    select {
    case done <- true:
    default:
    }
    

    The other alternative, and my preferred one, is to not send things over done channels. Instead, close the channel. This causes all blocked receive operations to instantly return, all at the same time (instead of having to send each one a value), and prevents blocking in the function sending the quit signal if nothing is listening. This also lets you replace the channel with a chan struct{}, which is nice, because a struct{} has 0 size.

    Still, worth noting that closing a nil channel, instead of blocking, panics, so you still have to do a nil check on it.

    Edit: my preferred style on this:

    func myFunc(foo int, done chan<- struct{}) {
        if done != nil {
            defer close(done)
        }
        ....
    }
    

    Edit 2: You could even make it a variadic, which allows the done channel to be omitted, or more than one to be provided.

    func myFunc(foo int, done ...chan<- struct{}) {
        for _, d := range done {
            if d != nil {
                defer close(d)
            }
        }
        ....
    }
    ----
    myFunc(1)
    myFunc(2, ch1)
    myFunc(3, ch2, ch3, ch4)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题