您的代码看起来不错,您实现了Go模式中常用的代码。缺点是-
您为每个项目生成工作程序goroutine。廉价地生成goroutine不是免费的。另一种方法是生成N个工人并通过渠道向他们提供物品。像这样
package mainimport ( "fmt" "time")func main() { items := 100 concurrency := 10 in := make(chan int) ret := make(chan error) for x := 0; x < concurrency; x++ { go worker(in, ret) } go func() { for x := 0; x < items; x++ { // loop over all items in <- x } close(in) }() for err := range ret { if err != nil { fmt.Println(err.Error()) break } }}func worker(in chan int, returnChan chan error) { //fmt.Printf("PROCESSING (%v)n", x) for x := range in { if x == 95 { returnChan <- fmt.Errorf("Something not right") } else { returnChan <- nil } time.Sleep(10 * time.Millisecond) } returnChan <- fmt.Errorf("The End")}
*** 场
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)