Skip to content

Instantly share code, notes, and snippets.

@gigenthomas
Created March 28, 2025 02:16
Show Gist options
  • Save gigenthomas/88982feed43ef3a7cb14b83c92aa9548 to your computer and use it in GitHub Desktop.
Save gigenthomas/88982feed43ef3a7cb14b83c92aa9548 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
// Worker function that listens for a job on its own channel
func worker(id int, jobChannel chan int) {
for job := range jobChannel {
fmt.Printf("Worker %d processing job %d\n", id, job)
time.Sleep(time.Second) // Simulate work
}
}
func main() {
workerPool := make(chan chan int, 2) // Channel of job channels
// Creating two workers with their own channels
for i := 1; i <= 2; i++ {
jobChannel := make(chan int) // Each worker gets a job channel
workerPool <- jobChannel // Register worker's channel in the pool
go worker(i, jobChannel) // Start worker goroutine
}
// Dispatcher sends jobs
for j := 101; j <= 103; j++ {
jobChannel := <-workerPool // Get a worker's channel
fmt.Println("Dispatching job", j)
jobChannel <- j // Send job to worker
workerPool <- jobChannel // Put worker back in the pool
}
// Give time for workers to process before exiting
time.Sleep(3 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment