正确的等待去程序完成的方式 [英] proper way of waiting for a go routine to finish
问题描述
我想知道在退出程序之前等待去程序完成的正确方法。阅读一些其他答案似乎是一个布尔将会做的伎俩,如 p>
func do_stuff(done chan bool){
fmt.Println(做东西)
完成< - true
$ b $ func main(){
fmt.Println(Main)
完成:= make(chan bool)
go do_stuff (完成)
<-done
// <-done
}
我在这里有两个问题: 为什么< - done完全可以工作? 如果我取消注释最后一行,会发生什么情况?我有一个死锁错误。这是因为频道是空的,没有其他函数发送值给它? 如果我取消注释最后一行,会发生什么情况? 额外奖励,如果你在内存方面非常有限,你可以使用 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
< - done
完全可以工作?
>
done:= make(chan struct {})
和 done< - struct {} {}
, struct {}
保证使用0内存。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?
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.
这篇关于正确的等待去程序完成的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!