gogoroutinedefer-keyword

Is it possible to defer a 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.


Solution

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

    session, err := getSessionFromQueue()
    defer func() {
        go queueSession(session)
    }()