Do goroutines keep running even if main function is terminated?

Issue

I am running a server where main fires off several go routines. like this:

main() {
     go someFn(){
       // will run for infinite time()
     }
     go otherFn()
}

I have two doubts:

  1. what if the main function is exited? will these threads will still run or will terminate with the main function?

  2. if no, then what is the best method to make the main function run forever/ or run till I need it? currently, I am using select{} command for making it run forever! is there any better and more efficient method available than select{}

Solution

The program exits when the function main() returns.

If one of someFn or otherFn runs forever, then call that function directly at the end of main. The main function never exits with this change.

If neither function runs forever, the use a sync.WaitGroup to wait on the goroutines and then exit.

The empty select statement select {} efficiently blocks a goroutine forever.

Answered By – user13631587

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.