ProgramGuru

Goroutine Lifecycle

Start with Goroutine Lifecycle

In this lesson, explore goroutine lifecycle through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of goroutine lifecycle.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

A goroutine is created, scheduled, can block while waiting for data or a lock, and eventually returns. Returning from main ends the process; other goroutines are not automatically joined.

A clear lifetime contract identifies who starts the task, what can stop it, and who waits for it.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for goroutine lifecycleEach goroutine needs an explicit completion policy.Start workerStep 1Worker runsStep 2Worker calls DoneStep 3Wait returnsStep 4Each goroutine needs an explicit completion policy.
Each goroutine needs an explicit completion policy.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		fmt.Println("Worker completed")
	}()
	wg.Wait()
	fmt.Println("Main can exit")
}

Output

Worker completed
Main can exit

Trace what the program does

Wait keeps the main goroutine active until the worker calls Done. The deferred call also runs on normal return from the worker.

Avoid common mistakes

  • Do not use arbitrary sleep durations as a completion guarantee.
  • If Done is never called, Wait can remain blocked.

Try it yourself

Create two workers and ensure both report completion before main exits.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What happens if main returns while another goroutine is still working?
Choose one answer. You can try again.

Answer and explanation

The process exits without waiting for it

Correct. Wait keeps the main goroutine active until the worker calls Done.

What you should remember

You have practiced Goroutine Lifecycle in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: sync.WaitGroup →