Junior
Mis on goroutines?
sobes.tech AI
Vastus AI-lt
Lightweight execution threads managed by the Go runtime. They are created with the go keyword before calling a function.
Main features:
- Lower memory consumption: A goroutine starts with a small stack size (usually 2 KB), which can grow or shrink dynamically.
- Faster creation: Creating a goroutine is much faster than creating a system thread.
- Multiplexing onto system threads: Many 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
runtime.Gosched()calls).
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 main from finishing before goroutine
}
Comparison with threads:
| Attribute | Go Goroutines | OS Threads |
|---|---|---|
| Management | Go runtime | Operating system |
| Memory usage | Low, dynamic stack | High, fixed stack |
| Creation | Fast | Slow |
| Scheduling | Cooperative | Preemptive |
| Synchronization | Channels, sync package | Mutexes, OS semaphores |