How best do I keep a long running Go program, running?

后端 未结 6 1986
半阙折子戏
半阙折子戏 2020-12-04 13:22

I\'ve a long running server written in Go. Main fires off several goroutines where the logic of the program executes. After that main does nothing useful. Once main exits

6条回答
  •  醉梦人生
    2020-12-04 13:41

    Go's runtime package has a function called runtime.Goexit that will do exactly what you want.

    Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

    Example in the playground

    package main
    
    import (
        "fmt"
        "runtime"
        "time"
    )
    
    func main() {
        go func() {
            time.Sleep(time.Second)
            fmt.Println("Go 1")
        }()
        go func() {
            time.Sleep(time.Second * 2)
            fmt.Println("Go 2")
        }()
    
        runtime.Goexit()
    
        fmt.Println("Exit")
    }
    

提交回复
热议问题