简体   繁体   中英

why the unbuffered channel in the goroutine got this order

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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