Goroutine池
生活随笔
收集整理的這篇文章主要介紹了
Goroutine池
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
goroutine池的應用
- 本質上是生產者消費者模型
- 可以有效控制goroutine數量,防止暴漲
- 需求:
- 計算一個數字的各個位數之和,例如數字123,結果為1+2+3=6
- 隨機生成數字進行計算
- 控制臺輸出結果如下:
main.go
package mainimport ("fmt""math/rand" )type Job struct {Id intRandom int }type Result struct {job *Jobsum int }func createGoroutinePool(goNum int, jobChan chan *Job, resultChan chan *Result){// 根據goNum開啟多個goroutine執行for i := 0; i < goNum; i++ {go func(jobChan chan *Job, resultChan chan *Result) {// 處理每個jobChan中的數據并返回結果for job := range jobChan{random := job.Randomvar sum int// 計算每一位的和for random != 0 {tmp := random % 10sum += tmprandom /= 10}// 組織返回結果r := &Result{job: job,sum: sum,}// 將結果寫入通道resultChan<- r}}(jobChan, resultChan)} }func main() {// 工作通道jobChan := make(chan *Job, 128)// 結果通道resultChan := make(chan *Result,128)// 創建工作池執行任務createGoroutinePool(64, jobChan, resultChan)// 打印結果通道數據go func(resultChan chan *Result){for result := range resultChan{fmt.Printf("job id: %v random: %v result: %d\n", result.job.Id, result.job.Random, result.sum)}}(resultChan)var id intfor {id++r_num := rand.Int()job := &Job{Id: id,Random: r_num,}jobChan<-job} }總結
以上是生活随笔為你收集整理的Goroutine池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kubernetes通过containe
- 下一篇: Select多路复用