golang working with worker pool

In this code example, we are spawn up our worker, sends it some work and gets the results back.

In the worker function, notice the we are using "result <- (<-task * 100)" to get the value from task channel which is 0 or 1 and then multiple it by 100.


package main
import "fmt"

func worker(id int, task <-chan int, result chan<- int, errors chan<- error) {
    fmt.Printf("Worker: %d processing tasks \n", id)
    if id == 5 {
        errors <- fmt.Errorf("worker %d failed to process task %d", id, task)
    }
    // getting actula value from task and multiply with 100
    result <- (<-task * 100)
}

func main() {
    const numTask = 2
    tasks := make(chan int, numTask)
    results := make(chan int, numTask)
    errors := make(chan error, numTask)

    // starting our worker
    for i := 0; i < numTask; i++ {
        fmt.Printf("firing task %d \n", i)
        go worker(i, tasks, results, errors)
    }

    // send work to worker
    for i := 0; i < numTask; i++ {
        fmt.Printf("send task %d \n", i)
        tasks <- i
    }

    // wait and get results back
    for i := 0; i < numTask; i++ {
        select {
        case res := <-results:
            fmt.Printf("results: %d\n", res)
        case er := <-errors:
            fmt.Printf("results: %d\n", er)
        }
    }
}

 






Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20