Junior — Middle
Millised on gorutinite kasutamise eelised võrreldes lõngadega (threads)?
sobes.tech AI
Vastus AI-lt
Gorutines in Go are lightweight threads managed by the Go runtime, not the operating system. Their advantages over traditional threads:
- Less memory consumption: Gorutines occupy a few kilobytes of memory, while threads — megabytes.
- Fast creation and switching: Starting and switching between gorutines is much faster.
- Simple synchronization: Go provides channels for safe data exchange between gorutines, simplifying concurrent programming.
- Scalability: You can launch thousands or even millions of gorutines simultaneously.
Example of creating a gorutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start a goroutine
time.Sleep(time.Second) // wait for the goroutine to complete
}