Golang网课-worker pool练习
作者:互联网
1 package main 2 3 /* 使用goroutine和channel实现一个计算int64随机数各位数和的程序 4 1.开启一个goroutine循环生成int64类型的随机数,发送到jobChan 5 2.开启24个goroutine从jobChan中取出随机数计算各位数的和,将结果发送到resultChan 6 3.主goroutine从resultChan取出结果并打印到终端输出 */ 7 8 import ( 9 "fmt" 10 "math/rand" 11 "time" 12 ) 13 14 type Job struct { 15 num int64 16 } 17 18 type Result struct { 19 jobPtr *Job 20 sum int64 21 } 22 23 var jobChan = make(chan *Job, 100) //传输随机数的 channel 24 var resChan = make(chan *Result, 100) //传输求和结果的 channel 25 26 //1.开启一个goroutine循环生成int64类型的随机数,发送到jobChan 27 func generate(jobChan chan<- *Job) { 28 for { 29 x := rand.Int63() //产生随机数x 30 31 newJob := &Job{num: x} //产生Job结构体指针用于在通道jobChan中传输 32 33 jobChan <- newJob 34 35 time.Sleep(time.Millisecond * 500) 36 } 37 } 38 39 //2.开启24个goroutine从jobChan中取出随机数计算各位数的和,将结果发送到resultChan 40 func calc(jobChan <-chan *Job, resChan chan<- *Result) { 41 for { 42 //取值 43 temp_job := <-jobChan 44 n := temp_job.num 45 sum := int64(0) 46 //计算 47 for n > 0 { 48 sum += n % 10 49 n = n / 10 50 } 51 //把结果发送到resultChan 52 var temp_res = &Result{sum: sum, jobPtr: temp_job} 53 resChan <- temp_res 54 } 55 } 56 57 func main() { 58 go generate(jobChan) 59 60 for i := 0; i < 24; i++ { 61 go calc(jobChan, resChan) 62 } 63 64 //3.主goroutine从resultChan取出结果并打印到终端输出 65 for res := range resChan { 66 fmt.Printf("num is: %d, sum is: %d\n", res.jobPtr.num, res.sum) 67 } 68 }
标签:发送到,sum,goroutine,worker,Golang,jobChan,int64,随机数,pool 来源: https://www.cnblogs.com/vosoland/p/15034380.html