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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算