美文网首页
golang 并行执行任务的例子

golang 并行执行任务的例子

作者: shinwing | 来源:发表于2019-02-13 09:30 被阅读0次

出自 kubernetes/staging/src/k8s.io/client-go/util/workqueue/parallelizer.go

type DoWorkPieceFunc func(piece int)

// Parallelize is a very simple framework that allow for parallelizing

// N independent pieces of work.

func Parallelize(workers, pieces int, doWorkPiece DoWorkPieceFunc) {

    toProcess := make(chan int, pieces)

    for i := 0; i < pieces; i++ {

        toProcess <- i

    }

    close(toProcess)

    if pieces < workers {

        workers = pieces

    }

    wg := sync.WaitGroup{}

    wg.Add(workers)

    for i := 0; i < workers; i++ {

        go func() {

            defer utilruntime.HandleCrash()

            defer wg.Done()

            for piece := range toProcess {

                doWorkPiece(piece)

            }

        }()

    }

    wg.Wait()

}

相关文章

网友评论

      本文标题:golang 并行执行任务的例子

      本文链接:https://www.haomeiwen.com/subject/ccrreqtx.html