Junior — Middle
How to distinguish a goroutine from a regular thread in the operating system?
sobes.tech AI
Answer from AI
A goroutine is a lightweight thread of execution managed by the Go runtime, not the operating system. Main differences:
- Lightweight: Goroutines use much less memory (usually a few kilobytes of stack), whereas system threads require megabytes.
- Scheduling: Goroutines are scheduled by the Go runtime (M:N scheduler), not the OS. This allows running thousands of goroutines on multiple system threads.
- Creation: Creating a goroutine is very cheap — just write
go function(), whereas creating a system thread is more resource-intensive.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // starts a goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}
Thus, goroutines are an abstraction over OS threads, optimized for concurrent programming in Go.