Sobes.tech
Junior — Middle

Kas saaksite selgitada kergete voogude kontseptsiooni ja nende erinevusi tavapärastest täitmise voogudest?

sobes.tech AI

Vastus AI-lt

Lightweight threads (goroutines in Go) are an abstraction for concurrent code execution, which is lighter and more resource-efficient than traditional system threads.

Differences:

  • Resources: goroutines occupy much less memory (usually a few kilobytes), while a system thread requires much more (usually megabytes).
  • Scheduling: goroutines are scheduled by Go's scheduler within the process, not by the operating system, allowing quick switching between them.
  • Creation: starting a goroutine is very fast and cheap, and thousands or even millions can be created simultaneously.

Example of creating a goroutine:

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

func main() {
    go sayHello() // starts the function in a separate goroutine
    time.Sleep(time.Second) // waits for the goroutine to finish
}

Thus, lightweight threads enable efficient parallelism without significant overhead.