這是Go中慣用的工作線程池嗎?我正在嘗試用goroutines編寫一個(gè)簡單的工作池。我寫的代碼是慣用的嗎?如果沒有,那么應(yīng)該改變什么呢?我希望能夠?qū)⒆畲蠊ぷ骶€程數(shù)設(shè)置為5并阻塞,直到工作人員可用,如果所有5個(gè)工作線都忙。我如何將此擴(kuò)展到最多只有5名工作人員?我是否會(huì)產(chǎn)生靜態(tài)的5 goroutines,然后分別給它們work_channel?碼:package mainimport (
"fmt"
"math/rand"
"sync"
"time")func worker(id string, work string, o chan string, wg *sync.WaitGroup) {
defer wg.Done()
sleepMs := rand.Intn(1000)
fmt.Printf("worker '%s' received: '%s', sleep %dms\n", id, work, sleepMs)
time.Sleep(time.Duration(sleepMs) * time.Millisecond)
o <- work + fmt.Sprintf("-%dms", sleepMs)}func main() {
var work_channel = make(chan string)
var results_channel = make(chan string)
// create goroutine per item in work_channel
go func() {
var c = 0
var wg sync.WaitGroup
for work := range work_channel {
wg.Add(1)
go worker(fmt.Sprintf("%d", c), work, results_channel, &wg)
c++
}
wg.Wait()
fmt.Println("closing results channel")
close(results_channel)
}()
// add work to the work_channel
go func() {
for c := 'a'; c < 'z'; c++ {
work_channel <- fmt.Sprintf("%c", c)
}
close(work_channel)
fmt.Println("sent work to work_channel")
}()
for x := range results_channel {
fmt.Printf("result: %s\n", x)
}}
- 2 回答
- 0 關(guān)注
- 1015 瀏覽
添加回答
舉報(bào)
0/150
提交
取消