Middle
What are goroutines? How do they differ from regular threads?
sobes.tech AI
Answer from AI
Goroutines are lightweight execution threads in the Go language, managed by the Go runtime rather than the operating system. They allow functions to run concurrently with minimal memory and time overhead.
Differences from regular threads:
- Lightweight: Goroutines occupy much less memory (usually a few kilobytes of stack space), whereas system threads require significantly more resources.
- Scheduling: The Go runtime has an integrated scheduler that efficiently distributes goroutines across system threads.
- Scalability: Thousands or even millions of goroutines can be run simultaneously, which is practically impossible with system threads.
- Communication: Goroutines often interact via channels, simplifying synchronization and data exchange.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}