日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Goroutine池

發布時間:2025/3/21 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Goroutine池 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

goroutine池的應用

  • 本質上是生產者消費者模型
  • 可以有效控制goroutine數量,防止暴漲
  • 需求:
    • 計算一個數字的各個位數之和,例如數字123,結果為1+2+3=6
    • 隨機生成數字進行計算
  • 控制臺輸出結果如下:
job id: 164362 random: 3002688297310473558 result: 81 job id: 164363 random: 8188014692039052954 result: 84 job id: 164364 random: 9199514953162082256 result: 87 job id: 164365 random: 6547609431377245779 result: 96 job id: 164366 random: 5158862497998501304 result: 94 job id: 164367 random: 7591045689235318611 result: 84 job id: 164368 random: 4913457935486468007 result: 93 job id: 164369 random: 6484925446766292271 result: 94 job id: 164370 random: 1630566468428792798 result: 101 job id: 164371 random: 3999715154713986432 result: 96 job id: 164372 random: 8436839935373284876 result: 106 job id: 164373 random: 7590654756672405712 result: 88 job id: 164374 random: 5127823813978664887 result: 103 job id: 164375 random: 5630536624069526117 result: 77 job id: 164376 random: 3445557283367509019 result: 86 job id: 164377 random: 6087330610397339825 result: 83 job id: 164378 random: 3391465925899927215 result: 99

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池的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。