Chris G.
Chris G.

Reputation: 25974

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

Upvotes: 0

Views: 487

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49195

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.

Upvotes: 4

Related Questions