Sobes.tech
Junior — Middle

Kuidas on Go keeles goroutine'id rakendatud ja hallatud?

sobes.tech AI

Vastus AI-lt

In Go, goroutines are lightweight execution threads managed by the Go runtime, not the operating system. They allow writing concurrent code with minimal resource usage.

Key aspects of implementing and managing goroutines:

  • Creation: A goroutine is started with the keyword go before calling a function.
  • Scheduler: The Go runtime has its own scheduler that distributes goroutines across system threads (M:N scheduling).
  • Stack: Each goroutine has a dynamic stack that can grow and shrink as needed, starting with a few kilobytes.
  • Communication: Channels are used for synchronization and data exchange between goroutines.

Example of creating a goroutine:

func sayHello() {
    fmt.Println("Hello from goroutine")
}

func main() {
    go sayHello() // starts the goroutine
    time.Sleep(time.Second) // waits for the goroutine to complete
}

Thus, goroutines are an efficient way to execute code in parallel with minimal overhead.