Junior — Middle
What types of tasks can be effectively implemented using goroutines to improve performance?
sobes.tech AI
Answer from AI
Goroutines in Go are ideal for tasks that require concurrent execution and can be broken down into independent parts. They are especially effective for:
- Input/output (I/O) operations, such as network requests or file handling, where a goroutine can wait for a response without blocking the main thread.
- Parallel data processing, for example, when processing large arrays or data streams.
- Implementing concurrent servers and clients, where multiple connections are handled simultaneously.
An example of using goroutines for parallel execution of multiple tasks:
package main
import (
"fmt"
"time"
)
func worker(id int) {
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
for i := 1; i <= 5; i++ {
go worker(i) // start a goroutine
}
time.Sleep(2 * time.Second) // wait for all goroutines to finish
}
Thus, goroutines allow efficient utilization of CPU resources and I/O waiting, increasing the overall performance of the application.