Senior
Live coding: there is an array of numbers from 1 to 10, you need to square them, parallelize the calculations in three workers. The number of workers should be a constant. For each number, output the ID of the worker processing it.
sobes.tech AI
Answer from AI
go package main
import ( "fmt" "sync" )
const workerCount = 3
func worker(id int, jobs <-chan int, wg *sync.WaitGroup) { defer wg.Done() for num := range jobs { result := num * num fmt.Printf("Worker %d processed number %d: %d\n", id, num, result) } }
func main() { numbers := []int{1,2,3,4,5,6,7,8,9,10} jobs := make(chan int, len(numbers)) var wg sync.WaitGroup
// Launch workers
for i := 1; i <= workerCount; i++ {
wg.Add(1)
go worker(i, jobs, &wg)
}
// Send numbers for processing
for _, num := range numbers {
jobs <- num
}
close(jobs)
wg.Wait()
}
In this example, a channel `jobs` is created, into which numbers from 1 to 10 are sent. Three workers read from the channel in parallel, square the number, and output the worker ID and the result. The number of workers is set by the constant `workerCount`.