本文介绍了在Golang的goroutines完成之前阻止main()函数终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 包主 导入fmt func printElo(){ fmt.Printf(Elo \\\)} func printHello(){ fmt。 printf(Hello \\\)} func main(){ fmt.Printf(This will print。)i:= 0 for i go printElo() go printHello() i ++ } } 这个程序的输出只是This will print。 goroutines printElo()和 printHello 的输出将不会被发射,因为我猜测 main()函数线程将在goroutine有机会开始执行之前完成。 使类似代码工作的惯用方法是什么在Golang中并不会过早终止?解决方案最简单,最干净和可伸缩的方法是使用 sync.WaitGroup : var wg =& sync.WaitGroup {} func printElo(){ defer wg.Done ) fmt.Printf(Elo \\\)} func printHello(){推迟wg.Done() fmt。 printf(Hello \\\)} func main(){ fmt.Printf(This will print。)i:= 0 for i wg.Add(1) go printElo() wg.Add(1) go printHello() i ++ } wg.Wait()} 输出(在 Go Playground ): 这将print.Hello Elo 你好 Elo 你好 Elo 你好 Elo 你好 Elo 你好 Elo 你好 Elo 你好 Elo 你好 Elo 你好 Elo 使用同步进行简单的规则 .WaitGroup : 致电 WaitGroup.Add() =https://golang.org/ref/spec#Go_statements =noreferrer> go 声明 建议致电 WaitGroup.Done() 延迟,所以即使goroutine发生混乱如果您想将 WaitGroup 传递给其他函数(并且不使用全局变量),则必须传递一个指向它的指针,否则将复制 WaitGroup (这是一个结构体),并且副本上调用的 Done()方法不会不要在原始 上观察Have loook at this contrived example:package mainimport "fmt"func printElo() { fmt.Printf("Elo\n")}func printHello() { fmt.Printf("Hello\n")}func main() { fmt.Printf("This will print.") i := 0 for i < 10 { go printElo() go printHello() i++ }}The output of this program would be just "This will print". Output of goroutines printElo() and printHello will not be emitted because, I guess, the main() function thread will finish before the goroutines have a chance to even start executing.What is the idiomatic way to make similar code work in Golang and not terminate prematurely? 解决方案 Simplest, cleanest and "scalable" way to do it is to use a sync.WaitGroup:var wg = &sync.WaitGroup{}func printElo() { defer wg.Done() fmt.Printf("Elo\n")}func printHello() { defer wg.Done() fmt.Printf("Hello\n")}func main() { fmt.Printf("This will print.") i := 0 for i < 10 { wg.Add(1) go printElo() wg.Add(1) go printHello() i++ } wg.Wait()}Output (try it on the Go Playground):This will print.HelloEloHelloEloHelloEloHelloEloHelloEloHelloEloHelloEloHelloEloHelloEloHelloEloSimple "rules" to follow when doing it with sync.WaitGroup:call WaitGroup.Add() in the "original" goroutine (that starts a new) before the go statementrecommended to call WaitGroup.Done() deferred, so it gets called even if the goroutine panicsif you want to pass WaitGroup to other functions (and not use a global variable), you must pass a pointer to it, else the WaitGroup (which is a struct) would be copied, and the Done() method called on the copy wouldn't be observed on the original 这篇关于在Golang的goroutines完成之前阻止main()函数终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-21 02:11