dtj4307 2017-12-04 04:05
浏览 27
已采纳

例行泄漏会发生在具有一个缓冲器的通道中,该缓冲器具有两个输入但只有一个输出吗?

I have a function that is used to forward a message between two io.ReadWriters. Once an error happens, I need to log the error and return. But I think I may have a goroutine leakage problem in my code:

func transport(rw1, rw2 io.ReadWriter) error {
    errc := make(chan error, 1) // only one buffer
    go func() {
        _, err := io.Copy(rw1, rw2)
        errc <- err
    }()

    go func() {
        _, err := io.Copy(rw2, rw1)
        errc <- err
    }()

    err := <-errc // only one error catched
    if err != nil && err == io.EOF {
        err = nil
    }
    return err
}

Because there is only one error can be caught in this function, will the second goroutine exit and garbaged normally? Or should I write one more err <- errc to receive another error.

  • 写回答

1条回答 默认 最新

  • dpdx51205 2017-12-04 04:10
    关注

    The value from one goroutine is received and the other is buffered. Both goroutines can send to the channel and exit. There is no leak.

    You might want to receive both values to ensure that application detects an error when the first goroutine to send is successful and the second goroutine encounters an error.

    var err error
    for i := 0; i < 2; i++ {
      if e := <-errc; e != nil {
        err = e
      }
    }
    

    Because io.Copy does not return io.EOF, there's no need to check for io.EOF when collecting the errors.

    The code can be simplified to use a single goroutine:

    errc := make(chan error, 1)
    go func() {
        _, err := io.Copy(rw1, rw2)
        errc <- err
    }()
    
    _, err := io.Copy(rw2, rw1)
    
    if e := <-errc; e != nil {
       err = e
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!