Junior — Middle
What is your experience in developing applications that use multithreading and parallel computing?
sobes.tech AI
Answer from AI
Concurrency in Go is implemented through goroutines — lightweight threads managed by the Go runtime. For parallel computations, goroutines are often used together with channels for synchronization and data exchange.
For example, you can launch multiple goroutines for parallel data processing and collect results via channels:
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
results <- j * 2 // simple processing
}
}
func main() {
jobs := make(chan int, 5)
results := make(chan int, 5)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
for a := 1; a <= 5; a++ {
fmt.Println(<-results)
}
}
This approach allows efficient CPU resource utilization and writing scalable applications with parallel processing.