proper way of waiting for a go routine to finish

牧云@^-^@ 提交于 2019-11-28 05:26:37

问题


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?


回答1:


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.




回答2:


Listening to channel <- done, is a blocking operation, so your program won't continue until true or false is sent i.e. done <- true.

Your question can have a few different answers depending on the circumstance.

For instance, suppose you wanted to parallelize a series of function calls that take a long time.

I would use the sync package for this

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            longOp()
            wg.Done()
        }()
    }
    // will wait until wg.Done is called 10 times
    // since we made wg.Add(1) call 10 times
    wg.Wait()
}

func longOp() {
    time.Sleep(time.Second * 2)
    fmt.Println("long op done")
}


来源:https://stackoverflow.com/questions/25954481/proper-way-of-waiting-for-a-go-routine-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!