dongxie3352 2016-10-06 14:51
浏览 40
已采纳

是否可以推迟goroutine?

is there a possible in go to defer a go routine, or a way to achieve the desired behaviour? The following background: I am pooling connections to a database in a channel. Basically in a handler I call

session, err := getSessionFromQueue()
// ...
// serving content to my client
// ...
go queueSession(session)

What I really would like to do is:

session, err := getSessionFromQueue()
defer go queueSession(session)
// ...
// serving content to my client
// ...

to avoid that my handler is hanging/crashing at some point and the session is not properly returned to the queue. The reason I want to run it as a go routine is that queueSession is potentially blocking for 1 second (in case the queue is full I wait for one second before I completely close the session).

Update

@abhink got me on the right track there. I solved the problem by putting the call to a goroutine in queueBackend.

func queueSession(mongoServer *Server) {
    go func(mongoServer *Server) {
        select {
        case mongoQueue <- mongoServer:
            // mongoServer stored in queue, done.
        case <- time.After(1 * time.Second):
            // cannot queue for whatever reason after 1 second
            // abort
            mongoServer.Close()
        }
    }(mongoServer)
}

Now I can simply call

defer queueSession(session)

and it is run as a goroutine.

  • 写回答

1条回答 默认 最新

  • dongzhengzhong1282 2016-10-06 14:54
    关注

    There is no way to directly defer a goroutine. You can try something like this:

    session, err := getSessionFromQueue()
    defer func() {
        go queueSession(session)
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!