在Golang的goroutines完成之前阻止main()函数终止 [英] Prevent the main() function from terminating before goroutines finish in Golang
问题描述
包主
导入fmt
func printElo(){
fmt.Printf(Elo \\\
)
}
func printHello(){
fmt。 printf(Hello \\\
)
}
func main(){
fmt.Printf(This will print。)
i:= 0
for i < 10 {
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 < 10 {
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 main
import "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.Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Hello
Elo
Simple "rules" to follow when doing it with sync.WaitGroup
:
- call
WaitGroup.Add()
in the "original" goroutine (that starts a new) before thego
statement - recommended to call
WaitGroup.Done()
deferred, so it gets called even if the goroutine panics - if you want to pass
WaitGroup
to other functions (and not use a global variable), you must pass a pointer to it, else theWaitGroup
(which is a struct) would be copied, and theDone()
method called on the copy wouldn't be observed on the original
这篇关于在Golang的goroutines完成之前阻止main()函数终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!