Principal
What is a goroutine and how does it differ from an OS thread?
sobes.tech AI
Answer from AI
A goroutine is a lightweight thread of execution implemented at the language level (for example, in Go). Unlike OS threads, goroutines are managed by the language runtime rather than the operating system kernel.
Main differences:
- Lightweight: goroutines occupy much less memory (usually a few kilobytes of stack), whereas an OS thread requires much more resources.
- Scheduling: goroutines are scheduled by the language runtime's scheduler, allowing efficient context switching without system calls.
- Scalability: thousands or even millions of goroutines can be launched, whereas such scale is often impossible with OS threads due to resource limitations.
Example in Go:
func main() {
go func() {
fmt.Println("Goroutine is running")
}()
time.Sleep(time.Second) // Wait for the goroutine to finish
}
Here, go starts a function as a goroutine, which runs concurrently with the main thread.