Concurrent execution model in Go - Time & Space Complexity
When programs run tasks at the same time, it changes how long things take. We want to see how running tasks together affects the total work done.
How does doing many tasks at once change the time needed as we add more tasks?
Analyze the time complexity of the following code snippet.
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(1 * time.Second) // simulate work
fmt.Println("Worker", id, "done")
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
}
This code runs 5 workers at the same time, each doing a 1-second task concurrently.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Starting 5 concurrent worker tasks.
- How many times: 5 times, once per worker.
Each worker runs independently, so total time depends on the longest single task, not the sum.
| Input Size (n) | Approx. Operations (seconds) |
|---|---|
| 5 | 1 (all run together) |
| 10 | 1 (still all run together) |
| 100 | 1 (assuming enough resources to run all) |
Pattern observation: Total time stays about the same as tasks increase, if they run truly in parallel.
Time Complexity: O(1)
This means the total time does not grow with more tasks because they run at the same time.
[X] Wrong: "Adding more concurrent tasks always makes the program slower because it does more work."
[OK] Correct: When tasks run at the same time, total time depends on the longest task, not the number of tasks.
Understanding how concurrency affects time helps you explain real programs that do many things at once. It shows you can think about how work spreads out over time.
"What if each worker took different amounts of time? How would that affect the total time complexity?"