Worker Pools
This Go code demonstrates a simple worker pool pattern where multiple worker goroutines process jobs concurrently. Let's go through it with inline comments:
Output
Explanation:
package main
: Indicates that this Go file belongs to the main executable package.import (...)
: Imports necessary packages, including "fmt" for formatting and printing, and "time" for handling time-related operations.func worker(id int, jobs <-chan int, results chan<- int) { ... }
: Defines a worker function that processes jobs received from the 'jobs' channel and sends results to the 'results' channel.for j := range jobs { ... }
: The worker goroutine loops over jobs received from the 'jobs' channel. The loop continues until the 'jobs' channel is closed.jobs <- j
: Sends the current job to the worker goroutine.time.Sleep(time.Second)
: Simulates work by sleeping for one second.results <- j * 2
: Sends the result (j * 2) to the 'results' channel.func main() { ... }
: The main function, where the execution of the program begins.jobs := make(chan int, numJobs)
: Creates a buffered channel named 'jobs' for sending jobs to worker goroutines. The buffer size is set to the number of jobs to allow non-blocking sends.results := make(chan int, numJobs)
: Creates a buffered channel named 'results' for receiving results from worker goroutines.for w := 1; w <= 3; w++ { go worker(w, jobs, results) }
: Launches three worker goroutines, each with its own ID, 'jobs' channel for receiving jobs, and 'results' channel for sending results.for j := 1; j <= numJobs; j++ { jobs <- j }
: Sends five jobs to the 'jobs' channel.close(jobs)
: Closes the 'jobs' channel to indicate that no more jobs will be sent.for a := 1; a <= numJobs; a++ { <-results }
: Receives and discards results from the 'results' channel. This loop ensures that all results are processed.
This code demonstrates the basic concept of a worker pool pattern in Go, where multiple worker goroutines concurrently process jobs. The worker goroutines are launched as separate goroutines, and jobs are sent to them via a channel. Results are collected through another channel. The program waits for all results to be processed before exiting.
Last updated
Was this helpful?