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

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。