Implementing a worker pool in Go is an efficient way to manage concurrent tasks, improving performance by limiting the number of goroutines that execute simultaneously. A worker pool helps in creating a balance between task submission and execution, ensuring system resources are utilized effectively.
package main
import (
"fmt"
"sync"
)
type Job struct {
ID int
}
func worker(jobs <-chan Job, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("Processing job ID: %d\n", job.ID)
}
}
func main() {
const numWorkers = 3
jobs := make(chan Job, 10)
var wg sync.WaitGroup
// Start workers
for w := 0; w < numWorkers; w++ {
wg.Add(1)
go worker(jobs, &wg)
}
// Send jobs to the workers
for i := 1; i <= 10; i++ {
jobs <- Job{ID: i}
}
close(jobs) // Close the jobs channel
wg.Wait() // Wait for all workers to finish
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?