concurrency
2w ago

What Are Goroutines?

33 views • 1 upvotes

A goroutine is a lightweight thread of execution managed by the Go runtime. It's the fundamental unit of concurrency in Go and one of the language's most powerful features.

Key Characteristics

  • Lightweight: Initial stack size of only ~2KB (vs 1-2MB for OS threads)
  • Cheap to create: Can spawn millions of goroutines with minimal overhead
  • Managed by Go runtime: Scheduler multiplexes goroutines onto OS threads
  • Cooperative scheduling: Goroutines yield control at specific points
  • Growing stacks: Stack grows and shrinks dynamically as needed
  • No direct control: You cannot directly kill or pause a goroutine

Simple Example

go
package main

import (
    "fmt"
    "time"
)

func sayHello(name string) {
    fmt.Printf("Hello from %s!\n", name)
}

func main() {
    // Launch goroutines
    go sayHello("goroutine 1")
    go sayHello("goroutine 2")
    go sayHello("goroutine 3")
    
    // Wait for goroutines to finish
    time.Sleep(1 * time.Second)
    
    fmt.Println("Main function exits")
}
Output:
code
Hello from goroutine 3!
Hello from goroutine 1!
Hello from goroutine 2!
Main function exits

Was this helpful?

Difficulty & Status

easy
Lvl. 2
Community Verified
Progress: 11%
Answered by: shubham vyasPrev TopicNext Topic