Middle
Tell me about goroutines in Go
sobes.tech AI
Answer from AI
Goroutines are lightweight execution threads in the Go language that allow functions to run concurrently with minimal memory and time overhead. They are managed by the Go runtime, not the operating system, making them more efficient compared to traditional threads.
A goroutine is started using the go keyword before a function call:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // starts a goroutine
time.Sleep(time.Second) // gives the goroutine time to execute
}
Goroutines use channels for synchronization and data exchange, simplifying concurrent programming without explicit locks.
Main advantages:
- Very low overhead for creation and context switching.
- Simple synchronization via channels.
- Efficient utilization of multi-processor systems.