在Golang的goroutines完成之前阻止main()函数终止 [英] Prevent the main() function from terminating before goroutines finish in Golang

查看:1322
本文介绍了在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 < 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




上观察

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 the go 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 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()函数终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆