why the unbuffered channel in the goroutine got this order

Issue

I’m writing some golang concurrency codes with goroutines and channels
here’s my codes:

package main

import "fmt"

func main() {
    in := make(chan int)

    go func() {
        fmt.Println("Adding num to channel")
        in <- 1
        fmt.Println("Done")
    }()
    val := <- in
    fmt.Println(val)
}

I make an unbuffered channel, in my opinion, The channel inside must wait until the channel outside reads it,and the output may like this :

Adding num to channel
1
Done

But in fact, the output is :

Adding num to channel
Done
1

I’m so confused that why the inside unbuffered channel just run without waiting for reading

Solution

Your interpretation of the output is incorrect. The goroutine did write to the channel, at which point the main goroutine did read, however the printf for “Done” executed before the printf for the value.

Synchronization operations establish a “happened before” relationship between goroutines. When the goroutine wrote the channel, the only thing that is guaranteed to happen before the channel write is the first println in the goroutine. Once the channel write and the corresponding read is done, the remaining of the goroutine and the main goroutine can execute in any order.

In your case, the goroutine executed before the main goroutine.

Answered By – Burak Serdar

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.