dongzhun1857 2015-09-20 23:42
浏览 23
已采纳

当非阻塞读取行挂起时,goroutine泄漏

Assuming you have a structure like this:

ch := make(chan string)
errCh := make(chan error)
go func() {
    line, _, err := bufio.NewReader(r).ReadLine()
    if err != nil {
        errCh <- err
    } else {
        ch <- string(line)
    }
}()
select {
case err := <-errCh:
    return "", err
case line := <-ch:
    return line, nil
case <-time.After(5 * time.Second):
    return "", TimeoutError
}

In the case of the 5 second timeout, the goroutine hangs until ReadLine returns, which may never happen. My project is a long-running server, so I don't want a buildup of stuck goroutines.

  • 写回答

1条回答 默认 最新

  • duanmu5641 2015-09-21 01:33
    关注

    ReadLine will not return until either the process exits or the method reads a line. There's no deadline or timeout mechanism for pipes.

    The goroutine will block if the call to ReadLine returns after the timeout. This can be fixed by using buffered channels:

    ch := make(chan string, 1)
    errCh := make(chan error, 1)
    

    The application should call Wait to cleanup resources associated with the command. The goroutine is a good place to call it:

    go func() {
      line, _, err := bufio.NewReader(r).ReadLine()
      if err != nil {
        errCh <- err
      } else {
        ch <- string(line)
      }
      cmd.Wait() // <-- add this line
    }()
    

    This will cause the goroutine to block, the very thing you are trying to avoid. The alternative is that the application leaks resources for each command.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'