Add worker pools
This commit is contained in:
parent
5112447dfb
commit
9430f69b87
6
main.go
6
main.go
@ -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()
|
||||||
}
|
}
|
||||||
|
39
workerpools/workerpools.go
Normal file
39
workerpools/workerpools.go
Normal 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")
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user