golang 多协程处理任务
package main
import (
"fmt"
"runtime"
)
var workers = runtime.NumCPU()
type result struct {
jobname string
resultcode int
resultinfo string
}
type job struct {
jobname string
results chan<- result
}
func main() {
jobnames := []string{"1", "2", "3", "4", "5", "6", "7", "8"}
dorequest(jobnames)
}
func dorequest(jobnames []string) {
// 定义需要的channels切片
jobs := make(chan job, workers)
results := make(chan result, len(jobnames))
done := make(chan struct{}, workers)
/**
* 把任务写入 JobCh通道
**/
go func( jobs chan <- job, jobnames[]string, results chan <- result){
for _, jobname := range jobnames {
jobs <- job{jobname, results}
}
close(jobs)
}( jobs, jobnames, results)
/**
* 开启n个协程处理任务
**/
for i := 0; i < workers; i++ {
go func( done chan <- struct{}, jobs <- chan job){
for job := range jobs {
job.do()
}
done <- struct{}{}
}( done, jobs)
}
/**
* 查看任务是否完成
**/
go func( done <- chan struct{}, results chan result){
for i := 0; i < workers; i++ {
<-done
}
close(results)
}( done, results)
/**
* 取出结果
**/
for result := range results {
fmt.Printf("done: %s,%d,%s\n", result.jobname, result.resultcode, result.resultinfo)
}
}
func (job job) do() {
fmt.Printf("... doing work in [%s]\n", job.jobname)
// 模拟处理结果
if job.jobname == "8" {
job.results <- result{job.jobname, 0, "ok"}
} else {
job.results <- result{job.jobname, -1, "error"}
}
}