2016-10-06 14:51
浏览 39


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).


@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

Now I can simply call

defer queueSession(session)

and it is run as a goroutine.

1条回答 默认 最新

相关推荐 更多相似问题