doubingling4706 2018-06-06 20:53
浏览 39

goroutine泄漏与上下文超时?

In the code below, a client is putting a string on a service's input channel and listening for a reply on either an output or an error channel.

The context is set with a 5ms timeout.

func (s service) run() {
    <-s.input

    go func() {
        select {
        case <-s.ctx.Done():
            s.errs <- errors.New("ctx done")
            return
        }
    }()

    time.Sleep(10 * time.Millisecond)
    s.output <- 42
    fmt.Println("run exit")
}

The code times out correctly (due to the 10ms sleep) and outputs

error:  ctx done

However, the "run exit" is never printed.

Question: Is there a goroutine leak with processes stuck on

s.output <- 42

Go Playground example

  • 写回答

1条回答 默认 最新

  • dongxia9620 2018-06-28 11:10
    关注

    Context has timeout of 5 milliseconds and you sleep for 10 millisecond before this line s.output <-42 is run. So the context is timeout first and error occurs, that correct, but take a look at main function:

    select {
        case o := <-s.output:
            fmt.Println("output: ", o)
        case err := <-s.errs:
            fmt.Println("error: ", err)
        }
    

    The select statement has reached case err := <-s.errs so it will break the select and go to the end of main function => program exit Even if s.output <- 42 is call simultaneously with s.errs <- errors.New("ctx done") only one case has reached in select statement, if you need to reach second case, put a loop around select statement

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度