Junior — Middle
How can the results of five concurrently running goroutines be collected and processed?
sobes.tech AI
Answer from AI
To run five goroutines simultaneously and collect their results, you can use channels in Go. Each goroutine sends its result to the channel, and the main function reads from the channel the required number of times.
Example:
package main
import (
"fmt"
"sync"
)
func worker(id int, ch chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
// some work
result := id * 2
ch <- result
}
func main() {
ch := make(chan int, 5) // buffered channel
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, ch, &wg)
}
wg.Wait()
close(ch)
for res := range ch {
fmt.Println("Result:", res)
}
}
Here, worker is a goroutine that computes a result and sends it to the channel. The main function waits for all goroutines to finish using WaitGroup, then closes the channel and reads all results.