简体   繁体   English

为什么 goroutine 中的无缓冲通道得到这个顺序

[英]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:我正在用 goroutine 和通道编写一些 golang 并发代码,这是我的代码:

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:我做了一个无缓冲的通道,在我看来,里面的通道必须等到外面的通道读取它,output可能是这样的:

Adding num to channel
1
Done

But in fact, the output is:但实际上output是:

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.您对 output 的解释不正确。 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. goroutine 确实写入了通道,此时主 goroutine 确实读取了,但是“完成”的 printf 在值的 printf 之前执行。

Synchronization operations establish a "happened before" relationship between goroutines.同步操作在 goroutine 之间建立了“之前发生过”的关系。 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.当 goroutine 写入通道时,唯一保证在通道写入之前发生的事情是 goroutine 中的第一个 println。 Once the channel write and the corresponding read is done, the remaining of the goroutine and the main goroutine can execute in any order.一旦通道写入和相应的读取完成,剩下的 goroutine 和主 goroutine 可以以任意顺序执行。

In your case, the goroutine executed before the main goroutine.在您的情况下,goroutine 在主 goroutine 之前执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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