Sobes.tech
Junior — Middle

Millised on gorutinite kasutamise eelised võrreldes süsteemilõngadega rakenduste jõudluse parandamiseks?

sobes.tech AI

Vastus AI-lt

Goroutines in Go have several advantages over system threads:

  • Lightweight: goroutines occupy much less memory (usually a few kilobytes), whereas system threads require significantly more resources.
  • Scalability: thousands or even millions of goroutines can be started simultaneously, which is difficult with threads.
  • Fast context switching: the Go scheduler manages goroutines efficiently and switches between them faster than the OS switches between threads.
  • Simplicity of synchronization: built-in channels and other primitives simplify data exchange between goroutines.

Example of creating a goroutine:

package main
import (
    "fmt"
    "time"
)

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

func main() {
    go sayHello() // start goroutine
    time.Sleep(time.Second) // wait for it to execute
}