Concurrency and Goroutines

Concurrency is the ability to perform multiple tasks at the same time. Go was designed from the ground up to make concurrent programming simple, safe, and efficient.

What is a Goroutine?

A goroutine is a lightweight thread managed by the Go runtime. They are much cheaper to create than traditional OS threads, allowing a single program to easily run thousands of them simultaneously.

The go Keyword

To run a function concurrently, simply prefix the function call with the go keyword.

func doWork() {
    fmt.Println("Doing work...")
}

func main() {
    go doWork() // Starts a new goroutine
    fmt.Println("Main function continuing...")
}

Key Characteristics

  • Non-blocking: The go keyword returns immediately, and the function executes in the background.
  • Silent Death: If the main goroutine exits, all other goroutines are immediately killed, even if they haven’t finished.
  • Cooperative Multitasking: Go manages how goroutines are scheduled across available CPU cores automatically.