Where are those goroutines left?

I’m a bit curious how golang handle these goroutines which are still running but the main goroutine already terminate? like below code snippet:

package main

import (
	"fmt"
	"time"
)

func main(){
	message := make(chan string)
	go func(){
		<- message
		time.Sleep(1*time.Second)
		fmt.Println("working...")
	}()
	message <- "hello"
}

I’m sure the printing in goroutine will never get executed since main goroutine terminate before these tasks in goroutine. How does golang handle this remaining tasks?

Thanks
James

1 Like

When func main terminates, the whole process terminates and thus all goroutines inside it.
You can make main wait for all goroutines to finish by using a wait group.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.