【问题标题】:Golang end function after any go routine finishes [duplicate]任何go例程完成后的Golang结束函数[重复]
【发布时间】:2020-07-03 21:08:15
【问题描述】:

我有一个如下所示的主要功能:

func main() {
    go SyncRealTime()
    go SyncStale()
}

这两个功能都应该无限期地继续下去。我想main 到:

  • 只要两个 Goroutine 都在运行,就不会终止。
  • 如果任一 Goroutine 终止(即错误),则终止

在 Go 中这样做的惯用方式是什么?

【问题讨论】:

  • 来自go specProgram execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

标签: go


【解决方案1】:

这是一种做法:

func main() {
    c := make(chan string)
    go func() {
        SyncRealTime()
        c <- "SyncRealTime"
    }()

    go func() {
        SyncStale()
        c <- "SyncStale"
    }()

    firstDone := <-c
    fmt.Println(firstDone + " exited")
    // done
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-07
    • 2015-02-22
    • 1970-01-01
    • 2019-02-06
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多