Two goroutine in the same Channel – how are they executed?

Issue

When I take the tour of Golang from golang.org, there’s one code snippet I don’t understand:

func sum(a []int, c chan int, order int) {
    sum := 0
    for _, v := range a {
        sum += v
    }
    fmt.Println(order, a)
    c <- sum // 将和送入 c
}

func main() {
    a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    a1, a2 := a[:len(a)/2], a[len(a)/2:]

    go sum(a1, c, 1)
    x := <-c
    go sum(a2, c, 2)
    y := <-c
    //x := <-c
    //y := <-c
    // x, y := <-c, <-c // 从 c 中获取

    fmt.Println(x, y, x+y)
}

This is the output I expected:

1 [7 2 8]
2 [-9 4 0]
17 -5 12

and when I changed the code:

func main() {
    a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    a1, a2 := a[:len(a)/2], a[len(a)/2:]

    go sum(a1, c, 1)
    //x := <-c
    go sum(a2, c, 2)
    //y := <-c
    x := <-c
    y := <-c
    // x, y := <-c, <-c // 从 c 中获取

    fmt.Println(x, y, x+y)
}

Why is the output like this:

2 [-9 4 0] 
1 [7 2 8]
-5 17 12

Solution

the thing is u’ve missed the concept of concurrency
there is no guarantee in executing functions in exact order of calling them with go

the reason first code snippet works orderly is the x := <-c part
this line force your app to wait until c channel is filled with data so second goroutine wont be called

Answered By – CallMeLoki

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.