Created
February 24, 2023 15:02
-
-
Save abdulrahmanAlotaibi/b1290b5590915f5c75d40237288e0460 to your computer and use it in GitHub Desktop.
Creating a worker pool in Go using channel and go routines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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