Goroutine lifecycle - Time & Space Complexity
When working with goroutines, it is important to understand how their execution time grows as we create more of them.
We want to know how the time cost changes when the number of goroutines increases.
Analyze the time complexity of the following code snippet.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
n := 5
wg.Add(n)
for i := 0; i < n; i++ {
go func(i int) {
defer wg.Done()
fmt.Println(i)
}(i)
}
wg.Wait()
}
This code launches n goroutines, each printing a number, and waits for all to finish.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Starting and running
ngoroutines. - How many times: Exactly
ntimes, once per goroutine.
As the number of goroutines n increases, the total work to start and complete them grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 goroutine starts and prints |
| 100 | About 100 goroutine starts and prints |
| 1000 | About 1000 goroutine starts and prints |
Pattern observation: The total work grows directly with the number of goroutines.
Time Complexity: O(n)
This means the time to start and complete all goroutines grows in a straight line as you add more goroutines.
[X] Wrong: "Starting many goroutines happens instantly and does not add time."
[OK] Correct: Each goroutine takes some time to start and run, so more goroutines mean more total work and time.
Understanding how goroutine count affects execution time helps you write efficient concurrent programs and explain your reasoning clearly.
"What if each goroutine launched another goroutine inside it? How would the time complexity change?"
Practice
Solution
Step 1: Understand goroutine purpose
A goroutine lets your program run functions concurrently, meaning at the same time.Step 2: Compare options
Only Run multiple functions at the same time correctly describes this behavior. Other options are incorrect or unrelated.Final Answer:
Run multiple functions at the same time -> Option DQuick Check:
Goroutine = concurrent execution [OK]
- Thinking goroutines slow down the program
- Believing goroutines prevent program exit automatically
- Assuming goroutines fix code errors
doWork()?Solution
Step 1: Recall goroutine syntax
In Go, prefixing a function call withgostarts it as a goroutine.Step 2: Check options
Only go doWork() uses the correct syntax:go doWork(). Others are invalid.Final Answer:
go doWork() -> Option BQuick Check:
Start goroutine = go + function call [OK]
- Using keywords like 'start' or 'run' instead of 'go'
- Writing 'goroutine' as a keyword
- Adding extra words before 'go'
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello()
fmt.Println("Main function finished")
time.Sleep(100 * time.Millisecond)
}Solution
Step 1: Understand goroutine and main flow
The goroutine runssayHello()concurrently, printing "Hello from goroutine". The main function prints "Main function finished" immediately.Step 2: Consider the sleep delay
Thetime.Sleeppauses main to allow goroutine to run before program exits, so both prints appear.Final Answer:
Main function finished Hello from goroutine -> Option CQuick Check:
Sleep allows goroutine output after main print [OK]
- Ignoring sleep causes goroutine output to miss
- Assuming goroutine prints before main
- Expecting no output without sleep
package main
import "fmt"
func main() {
go func() {
fmt.Println("Inside goroutine")
}()
}Solution
Step 1: Analyze goroutine lifecycle
The main function starts a goroutine but then immediately exits, ending the program.Step 2: Effect on goroutine execution
Because main exits, the goroutine may not get time to run, so "Inside goroutine" might never print.Final Answer:
The goroutine will never run because main exits immediately -> Option AQuick Check:
Main exit stops goroutine early [OK]
- Thinking goroutine runs after main exits
- Assuming syntax error in anonymous function
- Believing a special import is needed
package main
import (
"fmt"
"time"
)
func main() {
for i := 1; i <= 3; i++ {
// Which option below is correct here?
}
time.Sleep(100 * time.Millisecond)
}Solution
Step 1: Understand variable capture in goroutines
Loop variableichanges during iterations; capturing it directly in goroutine causes all to print last value.Step 2: Use parameter to pass current value
Passingias a parameternto the goroutine fixes this, so each prints its own number.Final Answer:
go func(n int) { fmt.Println(n) }(i) -> Option AQuick Check:
Pass loop variable as parameter to goroutine [OK]
- Capturing loop variable directly causing all prints same value
- Passing wrong variable to goroutine
- Confusing parameter and captured variable
Ready to prove it?
Pass the test and this pattern moves unknown
