Junior — Middle
What is the difference between a goroutine and a system thread in the context of task execution?
sobes.tech AI
Answer from AI
A goroutine is a lightweight, managed unit of execution within the Go runtime that uses very little memory and can be run in large numbers simultaneously. A system thread is a heavier unit of scheduling by the operating system.
Main differences:
- Goroutines are much lighter in resources than system threads.
- Goroutine scheduling occurs within the Go runtime, not the OS.
- Thousands of goroutines can run concurrently, whereas system threads are usually fewer due to the overhead of creation and switching.
Example of creating a goroutine:
func task() {
fmt.Println("Executing task")
}
func main() {
go task() // start goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}
Thus, goroutines allow efficient execution of many tasks in parallel with lower overhead.