How do I find out if a goroutine is done, without blocking?

Issue

All the examples I’ve seen so far involve blocking to get the result (via the <-chan operator).

My current approach involves passing a pointer to a struct:

type goresult struct {
    result resultType;
    finished bool;
}

which the goroutine writes upon completion. Then it’s a simple matter of checking finished whenever convenient. Do you have better alternatives?

What I’m really aiming for is a Qt-style signal-slot system. I have a hunch the solution will look almost trivial (chans have lots of unexplored potential), but I’m not yet familiar enough with the language to figure it out.

Solution

You can use the “comma, ok” pattern (see their page on “effective go“):

foo     := <- ch; // This blocks.
foo, ok := <- ch; // This returns immediately.

Answered By – James Antill

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.