Thuta Learning
AdvancedProgrammingbeginner

Goroutines (Concurrency)

Relax. We'll talk through this in plain words — no textbook voice.

Goroutine is a lightweight concurrent task managed by the Go runtime. Adding go in front of a function call lets that function run alongside the main flow at the same time. It's useful for making lots of API calls, running background jobs, or building worker systems.

go
package main

import (
    "fmt"
    "time"
)

func worker(name string) {
    for i := 1; i <= 3; i++ {
        fmt.Println(name, "task", i)
        time.Sleep(100 * time.Millisecond)
    }
}

func main() {
    go worker("A")
    worker("B")
}

go worker("A") runs worker A as a goroutine. worker("B") runs in the main goroutine. Since the two run almost simultaneously, the output order can differ each time.

You should see
(Output order may vary) B task 1 A task 1 A task 2 B task 2 B task 3 A task 3

Info

Concurrency means managing multiple tasks at once. Parallelism means actually running them at the same time on multiple CPU cores. Go makes writing concurrent code easy.

Easy traps

  • Once the main function finishes, the program can exit — which means a background goroutine might get cut off before it's done. In a real project, wait for it with a channel or sync.WaitGroup.
Goroutines (Concurrency) | Thuta Learning