gobyexample/workerpools/workerpools.go

40 lines
678 B
Go

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")
}