Skip to content

Instantly share code, notes, and snippets.

@abdulrahmanAlotaibi
Created February 24, 2023 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdulrahmanAlotaibi/b1290b5590915f5c75d40237288e0460 to your computer and use it in GitHub Desktop.
Save abdulrahmanAlotaibi/b1290b5590915f5c75d40237288e0460 to your computer and use it in GitHub Desktop.
Creating a worker pool in Go using channel and go routines
package main
import (
"fmt"
"time"
)
func main() {
numJobs := 20
limit := numJobs * 2
jobs := make(chan int , numJobs)
results := make(chan int , numJobs)
// routines to handle the calculations
for w:= 1 ; w <= 3; w++ {
go worker(w, jobs, results)
}
for j:= 1; j <= numJobs ; j++ {
jobs <- j
}
close(jobs)
fmt.Print("Result after processing jobs: ")
for res:= range results {
fmt.Println("result is",res)
if res == limit {
fmt.Println("Reached the end", res)
close (results)
}
}
}
// result is send-only chan, jobs read-only
func worker(id int , jobs <- chan int, results chan <- int ){
for j:= range jobs {
fmt.Println("Worker: ", id, " started job" )
time.Sleep(time.Second)
fmt.Println("Worker: ", id, " has finished job", j)
results <- j * 2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment