duanlun1955 2016-01-03 11:02
浏览 37

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

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)
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2016-01-03 11:11
    关注

    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".

    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. This is not synchronized and you have no guarantee which will happen first.

    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数