Worker Pools
package main
import (
"fmt"
"time"
)
// worker function represents a worker that processes jobs
func worker(id int, jobs <-chan int, results chan<- int) {
// Loop over jobs received from the 'jobs' channel
for j := range jobs {
fmt.Println("worker", id, "started job", j)
// Simulate work by sleeping for one second
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
// Send the result (j * 2) to the 'results' channel
results <- j * 2
}
}
func main() {
const numJobs = 5
// Creating two channels: 'jobs' for sending jobs to workers, and 'results' for receiving results
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
// Launching three worker goroutines
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// Sending five jobs to the 'jobs' channel
for j := 1; j <= numJobs; j++ {
jobs <- j
}
// Closing the 'jobs' channel to indicate that no more jobs will be sent
close(jobs)
// Receiving results from the 'results' channel
for a := 1; a <= numJobs; a++ {
<-results
}
}Output
Last updated