简体   繁体   English

sync.WaitGroup-为什么.wait()之后出现go例程

[英]sync.WaitGroup - why one go routine comes after .wait()

From the following I get: 从以下内容中我得到:
Packing received cake: Strawberry Cake 包装收到的蛋糕:草莓蛋糕
Packing received cake: Strawberry Cake 包装收到的蛋糕:草莓蛋糕
Packing received cake: Strawberry Cake 包装收到的蛋糕:草莓蛋糕
Packing received cake: Strawberry Cake 包装收到的蛋糕:草莓蛋糕
We are done! 我们完了!
Packing received cake: Strawberry Cake 包装收到的蛋糕:草莓蛋糕

I did not expect "We are done!" 我没想到“我们完成了!” to be second last? 倒数第二?

package main

import (
    "fmt"
    // "strconv"
    // "time"
    "sync"
)

func makeCakeAndSend(cs chan string, wg *sync.WaitGroup) {
    cakeName := "Strawberry Cake "
    cs <- cakeName
    wg.Done()
}

func receiveCakeAndPack(cs chan string) {
    for s := range cs {
        fmt.Println("Packing received cake: ", s)
    }
}

func main() {
    var wg sync.WaitGroup
    cs := make(chan string)

    wg.Add(5)

    for i := 1; i <= 5; i++ {
        go makeCakeAndSend(cs, &wg)
    }

    // go receiveCakeAndPack(cs)

    go func() {
        for s := range cs {
            fmt.Println("Packing received cake: ", s)
        }
        close(cs)
    }()

    wg.Wait()

    fmt.Println("We are done!")

    var input string
    fmt.Scanln(&input)
}

It's perfectly normal. 这是完全正常的。 The wg.Wait() makes sure that all goroutines finished sending data to the channel before we continue, it doesn't synchronize the prints of "Packing received cake". wg.Wait()确保在继续操作之前,所有goroutine已完成向通道的数据发送,它不会同步“包装收到的蛋糕”的打印。

When everyone has finished sending the data down the channel, the channel has one item in it, right? 当每个人都完成了通道中的数据发送后,该通道中有一项,对吗? but the Waitgroup is finished. 但等待组已完成。

So you have a race condition where the main goroutine continues to "we are done" and the receiving goroutine receives and prints. 因此,您遇到了一种竞争情况,其中主goroutine继续“完成”,接收goroutine接收并打印。 This is not synchronized and you have no guarantee which will happen first. 这是不同步的,您不能保证会先发生。

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

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