What Happens When the main Goroutine Exits

When the main goroutine exits, the Go program terminates instantly, killing all other goroutines regardless of their state.

When the main goroutine exits, the entire program terminates immediately, killing all other running goroutines without waiting for them to finish. This behavior is inherent to the Go runtime and cannot be changed; if you need to ensure other goroutines complete their work, the main goroutine must wait for them using synchronization primitives like sync.WaitGroup.

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		defer wg.Done()
		time.Sleep(2 * time.Second)
		fmt.Println("Worker finished")
	}()

	fmt.Println("Main waiting...")
	wg.Wait() // Blocks until the worker goroutine calls Done()
	fmt.Println("Program exiting")
}