iT邦幫忙

2023 iThome 鐵人賽

DAY 1
0
自我挑戰組

Go語言自學挑戰系列 第 24

第二十五天:使用Golang實作Worker Pools

  • 分享至 

  • xImage
  •  

什麼是Worker Pools

worker pool也稱為thread pool,

其概念為讓固定數量的goroutine在後台運行,等待分配給它們工作,

當工作分配給worker pool時會在後台執行,而主goroutine繼續執行其他程式碼。


圖片來源:https://miro.medium.com/v2/resize:fit:4800/format:webp/1*Ya3fa36roBBhZlMl-kChXw.png

建立Worker Pool 的步驟

  1. 定義worker function
  2. 建立jobs & results channels
  3. 啟用goroutines
  4. 傳送工作到jobs channels
  5. 關閉jobs channels
  6. 由results channels接收結果
  7. 等待goroutines完成
  8. 關閉results channels

實作

實作https://www.scaler.com/topics/golang/workerpool-in-golang/ 之範例:

package main

import (
	"fmt"
	"time"
)
//STEP 1
// worker function 引數: id, a jobs channel, and a results channel
func worker(id int, jobs <-chan int, results chan<- int) {
	// iterates over the jobs channel
	for j := range jobs {
		fmt.Println("worker", id, "started job", j)
		time.Sleep(time.Second)
		fmt.Println("worker", id, "finished job", j)
		// sends the result to the results channel
		results <- j * 2
	}
}

func main() {
    //宣告工作數目
	const numJobs = 5
    
    //STEP 2:
	// 建立 jobs channel 
	jobs := make(chan int, numJobs)
	// 建立 results channel 
	results := make(chan int, numJobs)
    
    //STEP 3:
	// creates 3 goroutines for the worker function
	for w := 1; w <= 3; w++ {

		go worker(w, jobs, results)
	}
    
    //STEP 4:
	// 發送工作至 jobs channel
	for j := 1; j <= numJobs; j++ {
		jobs <- j
	}
    
    //STEP 5:
	// 關閉 jobs channel 
	close(jobs)

    //STEP 6:
	// 從 results channel接收結果
	for a := 1; a <= numJobs; a++ {
		<-results
	}
    
    //STEP 8:
	// 關閉  results channel 
	close(results)
}

輸出結果:

worker 3 started job 1
worker 1 started job 2
worker 2 started job 3
worker 1 finished job 2
worker 1 started job 4
worker 3 finished job 1
worker 3 started job 5
worker 2 finished job 3
worker 1 finished job 4
worker 3 finished job 5

參考資料

  1. https://gobyexample.com/worker-pools
  2. https://itnext.io/explain-to-me-go-concurrency-worker-pool-pattern-like-im-five-e5f1be71e2b0
  3. https://www.scaler.com/topics/golang/workerpool-in-golang/

上一篇
第二十四天:字串控制 String Functions
下一篇
第二十六天:加密crypto package
系列文
Go語言自學挑戰29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言