Skip to content

Instantly share code, notes, and snippets.

@rafiramadhana
Created January 16, 2021 13:45
Show Gist options
  • Save rafiramadhana/1ae7cba4361cfb2913e02a6783edb44d to your computer and use it in GitHub Desktop.
Save rafiramadhana/1ae7cba4361cfb2913e02a6783edb44d to your computer and use it in GitHub Desktop.
Simple Go Worker Pool
package main
import (
"log"
"time"
)
const (
NUMBER_OF_JOBS = 25
NUMBER_OF_WORKERS = 2
)
func worker(id int, jobChan <-chan int, resChan chan<- int) {
for j := range jobChan {
log.Printf("[W-%d] Started T-%d\n", id, j)
time.Sleep(500 * time.Millisecond)
log.Printf("[W-%d] Finished T-%d\n", id, j)
resChan <- j
}
}
func main() {
jobChan := make(chan int, NUMBER_OF_JOBS)
resChan := make(chan int, NUMBER_OF_JOBS)
// start workers
for w := 1; w <= NUMBER_OF_WORKERS; w++ {
go worker(w, jobChan, resChan)
}
// sending jobs
for j := 1; j <= NUMBER_OF_JOBS; j++ {
jobChan <- j
}
// NOTE: Close channel indicating that all jobs have
// been sent to workers.
close(jobChan)
for r := 1; r <= NUMBER_OF_JOBS; r++ {
<-resChan
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment