go实现work_pool
2022-05-14 本文已影响0人
小王同学123321
使用goroutine和channel实现一个计算int64随机数各位数和的程序
1,开启一个goroutine循环生成int64类型的随机数,发送到jobChan
2,开始24个goroutine从jobChan中随机取出随机数计算各位数的和,将结果发送到resutlChan
3,主goroutine从resultChan取出结果并打印到终端输出
//waitgroup版本
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type job struct {
value int64
}
type res struct {
job *job
sum int64
}
var wg sync.WaitGroup
var jobchan = make(chan *job,100)
var reschan =make(chan *res,100)
//定义一个只写的chan函数
func producer(pro chan <- *job){
defer wg.Done()
for{
tmpvalue := rand.Int63()
pro <- &job{
value:tmpvalue,
}
time.Sleep(500*time.Microsecond)
}
}
func coustomer(pro <- chan *job,result chan <- *res){
defer wg.Done()
for {
job := <- pro
sum := int64(0)
n := job.value
for n> 0 {
sum += n%10
n = n/10
}
newresult := &res{
job:job,
sum:sum,
}
result <- newresult
}
}
func main(){
wg.Add(1)
go producer(jobchan)
wg.Add(24)
for i:=0;i<24;i++{
go coustomer(jobchan,reschan)
}
for k := range reschan{
fmt.Printf("value:%d,sum:%d\n",k.job.value,k.sum)
}
}