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

在所有 goroutine bing 发出后,如何使用 goroutine 按顺序打印数字?


这是随机打印数字的代码:


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()

发出 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()

    }

我希望所有 goroutine 都被发出,然后让它们按顺序打印数字。


慕尼黑的夜晚无繁华
浏览 180回答 1
1回答

翻翻过去那场雪

func main() {&nbsp; &nbsp; wg.Add(10)&nbsp; &nbsp; count := 10&nbsp; &nbsp; cBegins := make([]chan interface{}, count)&nbsp; &nbsp; for i := range cBegins {&nbsp; &nbsp; &nbsp; &nbsp; cBegins[i] = make(chan interface{})&nbsp; &nbsp; }&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; cBegins[0] <- struct {}{}&nbsp; &nbsp; }()&nbsp; &nbsp; for i := 0; i < count; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go func(i int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <-cBegins[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("i = %d\n", i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if i < 9 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cBegins[i+1] <- struct {}{}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }(i)&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go