Implement a job queue in Go by using a buffered channel to hold tasks and a pool of goroutines to process them concurrently.
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for j := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, j)
time.Sleep(time.Second) // Simulate work
}
}
func main() {
var wg sync.WaitGroup
jobs := make(chan int, 100) // Buffered channel as the queue
// Start workers
for w := 1; w <= 3; w++ {
wg.Add(1)
go worker(w, jobs, &wg)
}
// Send jobs
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
wg.Wait()
}