Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. goroutine

goroutine

A goroutine is a lightweight thread provided by Go. By placing the go keyword before a function call, you can run that function concurrently in a separate execution flow.

Syntax

// Launches a function as a goroutine.
go functionName(args)

// Launches an anonymous function as a goroutine.
go func() {
    // Code that runs concurrently.
}()

// Goroutines are very lightweight — you can launch thousands to millions simultaneously.
// However, all goroutines are terminated when main() exits.

Goroutine characteristics

FeatureDescription
LightweightFar lighter than OS threads. The initial stack size is only a few KB, and grows dynamically as needed.
Managed by the Go runtimeThe Go runtime maps goroutines onto OS threads. It efficiently schedules N goroutines across M OS threads (the M:N model).
Asynchronous executionA function launched with go returns control immediately. The caller does not wait for the goroutine to finish.
Waiting for completionUse a channel or sync.WaitGroup to wait for a goroutine to complete.
Panic propagationA panic inside a goroutine does not propagate to the caller. Each goroutine must handle panics individually with recover().

Sample code

package main

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

// worker performs a task and signals completion via WaitGroup.
func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // Notifies the WaitGroup when the work is done.
    fmt.Printf("Worker %d: started\n", id)
    time.Sleep(time.Millisecond * 100) // Simulates a time-consuming task.
    fmt.Printf("Worker %d: done\n", id)
}

func main() {
    // Launching a simple goroutine.
    go fmt.Println("Output from another goroutine") // Runs asynchronously.

    // Use WaitGroup to wait for goroutines to finish.
    var wg sync.WaitGroup

    // Launch 5 goroutines.
    for i := 1; i <= 5; i++ {
        wg.Add(1)       // Increment the counter before launching the goroutine.
        go worker(i, &wg)
    }

    wg.Wait() // Block until all goroutines have finished.
    fmt.Println("All workers completed")

    // Launching anonymous functions as goroutines.
    // Pass the loop variable as an argument to capture its value correctly.
    var wg2 sync.WaitGroup
    results := make([]int, 5)
    for i := 0; i < 5; i++ {
        wg2.Add(1)
        go func(idx int) {
            defer wg2.Done()
            results[idx] = idx * idx // Each goroutine processes its own index independently.
        }(i) // Pass the loop variable i as an argument.
    }
    wg2.Wait()
    fmt.Println("Squared results:", results) // Prints '[0 1 4 9 16]'.
}

Overview

Goroutines are the foundation of concurrency in Go. Unlike OS threads, they are extremely lightweight, allowing thousands to millions of goroutines to run simultaneously. However, when goroutines share data, you must synchronize access to avoid race conditions.

When launching goroutines inside a loop, capturing the loop variable directly in a closure causes all goroutines to reference the same final value — a common bug. Always pass the variable as an argument instead.

To wait for goroutines to finish, use either 'sync.WaitGroup' or a 'channel'. For safe access to shared data, use 'sync.Mutex'.

If you find any errors or copyright issues, please .