Sobes.tech
Middle

//1-10 вывести квадраты, посчитать в нескольких потоках, worker pool

sobes.tech AI

Answer from AI

Below is a Go example that calculates the squares of numbers from 1 to 10 using a worker pool and multiple goroutines:

type Job struct {
    Number int
}

type Result struct {
    Number int
    Square int
}

func worker(jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
    defer wg.Done()
    for job := range jobs {
        results <- Result{Number: job.Number, Square: job.Number * job.Number}
    }
}

func main() {
    jobs := make(chan Job, 10)
    results := make(chan Result, 10)

    var wg sync.WaitGroup
    workerCount := 3 // number of workers

    for i := 0; i < workerCount; i++ {
        wg.Add(1)
        go worker(jobs, results, &wg)
    }

    // Sending tasks
    for i := 1; i <= 10; i++ {
        jobs <- Job{Number: i}
    }
    close(jobs)

    // Closing results channel after all workers finish
    go func() {
        wg.Wait()
        close(results)
    }()

    // Reading results
    for result := range results {
        fmt.Printf("%d^2 = %d\n", result.Number, result.Square)
    }
}

This example creates a pool of three workers that process numbers in parallel, calculating their squares. Channels are used for task transmission and result collection.

//1-10 вывести квадраты, посчитать в нескольких… - sobes.tech