-2

I have a main function that looks like so:

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

Both of these functions are supposed to continue indefinitely. I'd like for main to:

  • Not terminate as long as both Goroutines are running.
  • Terminate if either one of the Goroutines terminates (i.e. errors)

What is the idiomatic way of doing that in Go?

istrau2
  • 337
  • 5
  • 15
  • From the [go spec](https://golang.org/ref/spec#Program_execution) `Program 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.` – ks2bmallik Jul 04 '20 at 09:28

1 Answers1

1

This is a way of doing it:

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

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

    firstDone := <-c
    fmt.Println(firstDone + " exited")
    // done
}
Shang Jian Ding
  • 1,931
  • 11
  • 24