SyntaxStudy
Sign Up
Go Starting Goroutines
Go Beginner 1 min read

Starting Goroutines

A goroutine is a lightweight thread of execution managed by the Go runtime. Goroutines are far cheaper than OS threads: they start with a small stack (typically 2–8 KB) that grows and shrinks as needed. You start a goroutine by prefixing any function call with the `go` keyword. The called function runs concurrently with the rest of the program. The Go runtime schedules goroutines onto a small number of OS threads using an M:N scheduler. This means thousands or even millions of goroutines can run concurrently without overwhelming the operating system. The scheduler is cooperative and preemptive: goroutines yield at I/O, channel operations, and certain runtime calls, and the scheduler can also preempt long-running goroutines at safe points. When the main goroutine returns, the program exits immediately, regardless of any other goroutines that are still running. To wait for goroutines to finish, you need either a `sync.WaitGroup`, a channel, or another synchronisation mechanism. Using `time.Sleep` to wait is unreliable and should never be used in production code.
Example
package main

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

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // signal completion when function returns

    fmt.Printf("Worker %d starting\n", id)
    // Simulate work with a sleep
    time.Sleep(time.Duration(id) * 100 * time.Millisecond)
    fmt.Printf("Worker %d done\n", id)
}

func main() {
    const numWorkers = 5

    var wg sync.WaitGroup

    for i := 1; i <= numWorkers; i++ {
        wg.Add(1)
        go worker(i, &wg) // launch goroutine
    }

    fmt.Println("All workers launched, waiting...")
    wg.Wait() // block until all workers call wg.Done()
    fmt.Println("All workers finished")

    // Anonymous goroutine
    done := make(chan struct{})
    go func() {
        defer close(done)
        fmt.Println("Anonymous goroutine running")
    }()
    <-done // wait for the anonymous goroutine
}