douling0053 2017-03-24 14:26
浏览 47
已采纳

context.WithDeadline,同时传递上下文去例程?

context.WithDeadline while passing context to go routine?

I have put together some sample code that will start a new goroutine for every item in my slice. At the moment, this will wait for the done channel to be called len(slice) times.

However, I would also like to implement a timeout in the goroutines to event leaking. It seems that context.WithDeadline (or maybe WithTimeout?)is the appropriate function to use.

For example, lets say I want to pass in a 23 second deadline for all goroutines that are initialized from main(). However, its not clear to me how I should do this.

I have read godoc along with Go Concurrency Patterns: Context (on the go blog) but as a new gopher, I am none the wiser. Many of the examples that I have found use http.handler(or similar as examples and so they are a source of some confusion for me.

What is an appropriate way to pass in context with deadline / timeout here.

package main

import (
  "fmt"
  "time"
)

func sleepNow(i int, done chan bool) {
  time.Sleep(time.Duration(i) * time.Second)
  fmt.Println(i, "has just woken up from sleep and the time is", time.Now())

  done <- true
}

func main() {
  done := make(chan bool)
  numbersSlice := []int{10, 20, 30, 12}

  for _, v := range(numbersSlice){
    go sleepNow(v, done)
  }

  for x := 0; x < len(numbersSlice); x++ {
  <-done
  }
  fmt.Println("Looks like we are all done here!")

}
  • 写回答

1条回答 默认 最新

  • dos49618 2017-03-24 14:38
    关注

    All you need to do is get the context into the function where you want to use it. I many cases you can use a simple closure, or in this case, add it to the function arguments.

    Once you have the context in place, you can select on the Context.Done() channel to determine when it has expired.

    https://play.golang.org/p/q-n_2mIW2X

    func sleepNow(i int, ctx context.Context, wg *sync.WaitGroup) {
        defer wg.Done()
    
        select {
        case <-time.After(time.Duration(i) * time.Second):
            fmt.Println(i, "has just woken up from sleep and the time is", time.Now())
        case <-ctx.Done():
            fmt.Println(i, "has just been canceled")
        }
    }
    
    func main() {
        var wg sync.WaitGroup
        numbersSlice := []int{1, 5, 4, 2}
    
        ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    
        for _, v := range numbersSlice {
            wg.Add(1)
            go sleepNow(v, ctx, &wg)
        }
    
        wg.Wait()
        cancel()
    
        fmt.Println("Looks like we are all done here!")
    }
    

    You should also use a sync.WaitGroup rather than rely on counting tokens over channel, and use defer to call Done.

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

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题