goroutine的排序结果

时间:2019-07-06 18:31:13

标签: go concurrency goroutine channels

我在SO(Golang synchronization for several goroutines using channels)上发现了一个完全符合我想要的问题。

问题是我希望结果井然有序。以下是CeriseLimón

中答案的修改示例
func main() {
    const num_workers = 5
    results := make(chan string, num_workers)
    workCh := make(chan uint64)

    // Start workers
    var wg sync.WaitGroup
    wg.Add(num_workers)
    for i := 0; i < num_workers; i++ {
        go func(num int) {
            defer wg.Done()
            for w := range workCh {
                // simulate long processing time
                time.Sleep(time.Duration(rand.Intn(3) * 1000))

                results <- fmt.Sprintf("worker %d, task %d", num, w)
            }

        }(i)
    }

    // Close result channel when workers done
    go func() {
        wg.Wait()
        close(results)
    }()

    // Send work to be done
    go func() {
        for i := 0; i < num_workers; i++ {
            workCh <- uint64(i)
        }
        close(workCh)
    }()

    // Process results
    for r := range results {
        fmt.Println(r)
    }
}

play.golang.org

上面的示例给出了以下输出:

worker 4, task 4
worker 3, task 3
worker 1, task 1
worker 0, task 0
worker 2, task 2

是否可以像下面这样排序这些结果?

worker 0, task 0
worker 0, task 1
worker 1, task 2
worker 2, task 3
worker 3, task 4

更新示例:https://play.golang.org/p/86Et7R8jlcB

0 个答案:

没有答案