doushenyu8228 2018-08-09 14:05
浏览 57
已采纳

Golang缓冲通道在发送之前就已接收数据

I am very new to golang. I get very confused when testing how channel works in Golang today.

According to the tutorial:

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

My test program looks like this:

package main

import "fmt"

func main() {
    ch := make(chan int, 2)

    go func(ch chan int) int {
        for i := 0; i < 10; i++ {
            fmt.Println("goroutine: GET ", <-ch)
        }
        return 1
    }(ch)

    for j := 0; j < 10; j++ {
        ch <- j
        fmt.Println("PUT into channel", j)
    }
}

I get the output like this:

PUT into channel 0
PUT into channel 1
goroutine: GET  0
goroutine: GET  1
goroutine: GET  2
PUT into channel 2
PUT into channel 3
PUT into channel 4
PUT into channel 5
goroutine: GET  3
goroutine: GET  4
goroutine: GET  5
goroutine: GET  6
PUT into channel 6
PUT into channel 7
PUT into channel 8
PUT into channel 9

Notice that number 2 is fetched from the channel before even been put in the channel. why does this happen?

  • 写回答

1条回答 默认 最新

  • dongming6201 2018-08-09 16:09
    关注

    It doesn't. Your Println("PUT into channel") happens after you put it on the channel, meaning there's an opportunity for it to be read from the channel before that print statement is executed.

    The actual order of execution in your sample output is something along the lines of:

    1. Writer routine writes 2 to the channel.
    2. Reader routine receives 2 from the channel.
    3. Reader routine prints goroutine: GET 2.
    4. Writer routine prints PUT into channel 2

    Your reads and writes from/to the channel are happening in the expected order, it's just your print statements that make it appear to be out of order.

    If you changed the writer's order of operations to:

        fmt.Println("PUT into channel", j)
        ch <- j
    

    You would likely see output closer to what you're expecting. It still wouldn't necessarily exactly represent the order of operations, however, because:

    1. Execution is concurrent, but writes to stdout are synchronous
    2. Every function call and channel send/receive is an opportunity for the scheduler to switch, so even running with GOMAXPROCS=1, it could switch goroutines between the print and the channel operation (in the reader or the writer).

    TL;DR: don't read too much into the order of log messages when logging concurrent operations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计