Junior — Middle
What approaches and tools are used in Go for organizing parallel and asynchronous computations with goroutines?
sobes.tech AI
Answer from AI
In Go, goroutines are used to organize parallel and asynchronous computations — lightweight threads that are launched using the go keyword.
Main tools and approaches:
- Goroutines: allow functions to run in parallel without explicit management of OS threads.
- Channels: used for safe data exchange between goroutines and synchronization.
- select: an operator to wait on multiple channel operations, enabling handling data from multiple sources.
Example:
package main
import (
"fmt"
"time"
)
func worker(id int, ch chan<- string) {
time.Sleep(time.Second) // simulate work
ch <- fmt.Sprintf("Worker %d done", id)
}
func main() {
ch := make(chan string)
for i := 1; i <= 3; i++ {
go worker(i, ch)
}
for i := 1; i <= 3; i++ {
msg := <-ch
fmt.Println(msg)
}
}
In this example, three goroutines run in parallel, and a channel is used to receive results.
Thus, the combination of goroutines and channels is the main way to organize parallel and asynchronous computations in Go.