proper way of waiting for a go routine to finish

后端 未结 2 1474
无人及你
无人及你 2020-12-19 21:10

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 tric

2条回答
  •  天涯浪人
    2020-12-19 21:33

    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.

提交回复
热议问题