https://blog.csdn.net/qq_55752792/article/details/125917846
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
// Job struct
type Job struct {
ID int64
RandNum int64
}
// Result struct
type Result struct {
job Job
Total int64
}
var jobChan = make(chan Job, 10)
var resultChan = make(chan Result, 10)
// worker
func worker(wg *sync.WaitGroup) {
for job := range jobChan {
total := int64(0)
randNum := job.RandNum
for randNum != 0 {
total += randNum % 10
randNum /= 10
}
time.Sleep(1 * time.Second)
resultChan <- Result{job, total}
}
wg.Done()
}
// worker pool
func createWorkerPool(n int64) {
var wgPool sync.WaitGroup
for i := int64(0); i < n; i++ {
wgPool.Add(1)
go worker(&wgPool)
}
wgPool.Wait()
close(resultChan)
}
// create job
func createJob(n int64) {
for i := int64(0); i < n; i++ {
jobChan <- Job{i, rand.Int63n(999)}
}
close(jobChan)
}
// get result
func getResult() {
for r := range resultChan {
fmt.Println(r.job.ID, r.job.RandNum, r.Total)
}
}
func main() {
start := time.Now()
go createJob(1000)
go getResult()
createWorkerPool(50)
end := time.Now()
fmt.Println("start: ", start, ", end: ", end, ", total: ", end.Sub(start))
}
createWorkerPool 由10 增加至 50, 计算时间缩减,效率提高