Add worker pools

This commit is contained in:
Sangeeth Sudheer 2024-04-29 07:34:27 +05:30
parent 5112447dfb
commit 9430f69b87
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 43 additions and 2 deletions

View File

@ -11,7 +11,8 @@ package main
// import "git.sangeeth.dev/gobyexample/selectdefault" // import "git.sangeeth.dev/gobyexample/selectdefault"
// import "git.sangeeth.dev/gobyexample/closingchannels" // import "git.sangeeth.dev/gobyexample/closingchannels"
// import "git.sangeeth.dev/gobyexample/timers" // import "git.sangeeth.dev/gobyexample/timers"
import "git.sangeeth.dev/gobyexample/tickers" // import "git.sangeeth.dev/gobyexample/tickers"
import "git.sangeeth.dev/gobyexample/workerpools"
func main() { func main() {
// runes.Runes() // runes.Runes()
@ -25,5 +26,6 @@ func main() {
// selectdefault.SelectDefault() // selectdefault.SelectDefault()
// closingchannels.ClosingChannels() // closingchannels.ClosingChannels()
// timers.Timers() // timers.Timers()
tickers.Tickers() // tickers.Tickers()
workerpools.WorkerPools()
} }

View File

@ -0,0 +1,39 @@
package workerpools
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for job := range jobs {
fmt.Printf("worker %d processing job %d\n", id, job)
time.Sleep(time.Second)
fmt.Printf("worker %d finished job %d, sending result %d\n", id, job, job*2)
results <- job * 2
}
fmt.Println("Exiting worker", id)
}
func WorkerPools() {
numJobs := 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
for i := range 3 {
go worker(i, jobs, results)
}
for i := range numJobs {
jobs <- i + 1
}
close(jobs)
for range numJobs {
fmt.Println("Received result:", <-results)
}
fmt.Println("Exiting program")
}