Principal
What are goroutines in Go? How do they differ from OS threads?
sobes.tech AI
Answer from AI
Goroutines in Go are lightweight execution threads managed by the Go runtime, allowing functions to run concurrently.
Differences between a goroutine and an OS thread:
- Lightweight: Goroutines use much less memory (usually a few kilobytes) compared to OS threads, which are significantly larger.
- Scheduling: Goroutines are scheduled by the Go scheduler within a process, not by the OS, enabling faster and more efficient context switching.
- Scalability: Thousands or even millions of goroutines can be run simultaneously, which is not possible with OS threads due to resource limitations.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start a goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}