User Tools

Site Tools


go:concurrency:goroutine

Goroutine

What is it?

A goroutine is a lightweight thread managed by the Go runtime. You start it with the `go` keyword.

What is it used for?

  • Run tasks concurrently: I/O, API calls, background jobs.
  • Improve server throughput by doing work in parallel.

Example

package main
 
import (
    "fmt"
    "time"
)
 
func work(name string) {
    fmt.Println("start:", name)
    time.Sleep(200 * time.Millisecond)
    fmt.Println("done:", name)
}
 
func main() {
    go work("A")
    go work("B")
    time.Sleep(500 * time.Millisecond) // demo: wait a bit
}

Important notes

  • Goroutines may stop when `main` exits.
  • In real code, use `sync.WaitGroup` or `context` to control lifecycle.

Hard words (English)

  • lightweight /ˈlaɪtweɪt/: nhẹ, ít tài nguyên
  • thread /θred/: luồng
  • runtime /ˈrʌntaɪm/: môi trường chạy
  • concurrently /kənˈkɝːəntli/: đồng thời
  • throughput /ˈθruːpʊt/: thông lượng
  • lifecycle /ˈlaɪfˌsaɪkəl/: vòng đời
go/concurrency/goroutine.txt · Last modified: by phong2018