这是Go中惯用的工作线程池吗?
我正在尝试用goroutines编写一个简单的工作池。
我写的代码是惯用的吗?如果没有,那么应该改变什么呢?
我希望能够将最大工作线程数设置为5并阻塞,直到工作人员可用,如果所有5个工作线都忙。我如何将此扩展到最多只有5名工作人员?我是否会产生静态的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) }}
相关分类