Junior
What are the advantages of goroutines compared to threads?
sobes.tech AI
Answer from AI
Goroutines have several advantages:
- Lightweight: Goroutines consume much less memory (a few KB of stack by default compared to MBs for OS threads). This allows creating tens and hundreds of thousands of active goroutines.
- Go's multithreaded scheduler: The Go scheduler efficiently distributes goroutines across OS threads. A goroutine waiting for I/O operations does not block the execution of other goroutines on the same OS thread.
- Ease of creation: Goroutines are created using the
gokeyword, which is much simpler than working with OS thread APIs. - Safety: Go supports concurrent execution at the language level, using channels for safe data exchange between goroutines instead of shared memory and synchronization primitives (although mutexes are also available).
Example of creating a goroutine:
// Simple function
func sayHello() {
fmt.Println("Hello from goroutine!")
}
// Creating a goroutine
go sayHello()