16

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 Answer 1

23

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

session, err := getSessionFromQueue()
defer func() {
    go queueSession(session)
}()
1
  • thanks, that put me on the right track. I implemented it slightly different but using an anonymos function was a very good starting point. Oct 6, 2016 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.