简体   繁体   English

发射所有goroutine后如何使用goroutine按顺序打印数字

[英]How to print numbers in order using goroutine after emit all the goroutine

How to print numbers in order using goroutine after all goroutines bing emited?在所有 goroutine bing 发出后,如何使用 goroutine 按顺序打印数字?

Here is the code which print numbers in random:这是随机打印数字的代码:

func main() {

    var wg sync.WaitGroup
    wg.Add(10)
    for i := 1; i <= 10; i++ {
        go func(i int) {
            defer wg.Done()
            fmt.Printf("i = %d\n", i)
        }(i)
    }
    wg.Wait()

Emit goroutines in order to print numbers like below, it's not the solution I want.发出 goroutine 以打印如下数字,这不是我想要的解决方案。

func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 10; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            fmt.Printf("i = %d\n", i)
        }(i)
        wg.Wait()
    }

I want all goroutines being emited, and after then make them print numbers in order.我希望所有 goroutine 都被发出,然后让它们按顺序打印数字。


func main() {
    wg.Add(10)
    count := 10
    cBegins := make([]chan interface{}, count)
    for i := range cBegins {
        cBegins[i] = make(chan interface{})
    }
    go func() {
        cBegins[0] <- struct {}{}
    }()
    for i := 0; i < count; i++ {
        go func(i int) {
            defer wg.Done()
            <-cBegins[i]
            fmt.Printf("i = %d\n", i)
            if i < 9 {
                cBegins[i+1] <- struct {}{}
            }
        }(i)
    }

    wg.Wait()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM