Junior
Kuidas erinevad gorutined niitidest (niitidest)?
sobes.tech AI
Vastus AI-lt
Goroutines differ from threads (treads) in the following key aspects:
- Management: Goroutines are managed by the Go runtime, while threads are managed by the operating system. This makes switching between goroutines much easier and faster, as it does not require a kernel context switch.
- Costs: Creating and managing goroutines requires much fewer resources (memory and time) compared to threads. A goroutine starts with a very small stack (a few kilobytes), which can grow or shrink dynamically as needed, whereas threads have a fixed, often much larger stack.
- Scalability: Due to low costs, it is easy to create hundreds of thousands or even millions of goroutines in a single application, while creating the same number of threads quickly exhausts system resources.
- Scheduling: The Go scheduler multiplexes many goroutines onto fewer OS threads. This implements cooperative multitasking among goroutines on a single thread (with elements of preemption), while OS threads are managed by the OS scheduler, which uses preemptive multitasking.
| Aspect | Goroutines | Threads (Treads) |
|---|---|---|
| Management | Go runtime | Operating system |
| Costs | Low (memory, time) | High (memory, time) |
| Scalability | Very high | Limited by system resources |
| Scheduling | Go scheduler (cooperative) | OS scheduler (preemptive) |
| Stack | Dynamic, small | Fixed, often large |
Example of creating a goroutine:
package main
import (
"fmt"
"time"
)
func task(id int) {
fmt.Printf("Goroutine %d started\n", id)
time.Sleep(time.Second)
fmt.Printf("Goroutine %d finished\n", id)
}
func main() {
go task(1) // Creating a goroutine
go task(2) // Creating another goroutine
time.Sleep(2 * time.Second) // Waiting for goroutines to complete
fmt.Println("Main goroutine finished")
}