Junior
What are goroutines?
sobes.tech AI
Answer from AI
Lightweight execution threads managed by the Go runtime. They are created with the go keyword before a function call.
Main characteristics:
- Lower memory consumption: A goroutine starts with a small stack size (usually 2 KB), which can dynamically grow or shrink.
- Faster creation: Creating a goroutine is much faster than creating a system thread.
- Multiplexing onto system threads: Multiple goroutines can be multiplexed onto fewer system threads by the Go runtime scheduler.
- Cooperative scheduling: Goroutines are not preemptively interrupted; they voluntarily yield control to the scheduler (e.g., during blocking calls or explicit calls to
runtime.Gosched()).
Example of creation:
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine!")
}
func main() {
go sayHello() // Launch sayHello as a goroutine
fmt.Println("Hello from main function!")
time.Sleep(1 * time.Second) // To prevent the main function from finishing before the goroutine
}
Comparison with threads:
| Attribute | Go Goroutines | OS Threads |
|---|---|---|
| Management | Go runtime environment | Operating system |
| Memory usage | Low, dynamic stack | High, fixed stack |
| Creation | Fast | Slow |
| Scheduling | Cooperative | Preemptive |
| Synchronization | Channels, sync package | Mutexes, OS semaphores |