worker pool
type WorkerJob struct {
from int
size int
isConcept bool
}
jobCh := make(chan WorkerJob,100)
- 定义生产者
生成者负责创建job,并把job投入job channel
func producer(jobs chan WorkerJob){
job := WorkerJob{from:1,size:10}
jobs <- job
}
func worker(jobs chan WorkerJob,results chan WorkerResult ,wg *sync.WaitGroup){
for job := range jobs{
out := WorkerResult{jobId:job.id, message: cosumer(job.from,job.size,job.isConcept)}
results <- out
}
wg.Done()
}
func createWorkPool(numOfWorkers int,jobs chan WorkerJob,results chan WorkerResult){
var wg sync.WaitGroup
for i := 0; i < numOfWorkers ; i++{
wg.Add(1)
go worker(jobs,results,&wg)
}
wg.Wait()
close(results)
}
func cosumer(from,size int,isConcept bool)string{
//to do...
return "success"
}
jobCh := make(chan WorkerJob,100)
resultCh := make(chan WorkerResult,100)
//生产者创建job
go producer(jobCh)
done := make(chan bool)
go LogResult(done,resultCh)
//创建工作池,每个worker领取job开始工作
createPlateWorkPool(20,jobCh,resultCh)
<- done