proper way of waiting for a go routine to finish

Issue

I wish to know what is the proper way of waiting for a go routine to finish before exiting the program. Reading some other answers it seems that a bool chan will do the trick, as in Playground link

func do_stuff(done chan bool) {
    fmt.Println("Doing stuff")
    done <- true
}

func main() {
    fmt.Println("Main")
    done := make(chan bool)
    go do_stuff(done)
    <-done
    //<-done
}

I have two questions here:

  • why the <- done works at all?

  • what happens if I uncomment the last line? I have a deadlock error. Is this because the channel is empty and there is no other function sending values to it?

Solution

Why the <- done works at all?

  • It works because the runtime detects that you’re writing something to the channel somewhere else.

what happens if I uncomment the last line?

  • The runtime is smart enough to know that there’s nothing else being written and it deadlocks.

Bonus, if you’re extremely limited on memory, you can use done := make(chan struct{}) and done <- struct{}{}, struct{} is guaranteed to use 0 memory.

Answered By – OneOfOne

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.