douju5062 2019-05-28 13:43
浏览 59
已采纳

去同步和并发模型

I'm a new Go learner, and I'm following gobyexample.com to learn the basics. When I reach the "closing channels" section, the tutorial inserts this code snippet (I'll remove original comments):

    package main

    import "fmt"

    func main() {
        jobs := make(chan int, 5)
        done := make(chan bool)

       go func() {
           for {
               j, more := <-jobs
               if more {
                   fmt.Println("received job", j)
               } else {
                   fmt.Println("received all jobs")
                   done <- true
                   return
               }
           }
       }()

       for j := 1; j <= 18; j++ {
           jobs <- j
           fmt.Println("sent job", j)
       }
       close(jobs)
       fmt.Println("sent all jobs")

       <-done
    }

The original code was setting a 3 instead of a 18 in the job sender loop.

Executing this code in play.golang.org it is what I don't fully understand. It always outputs the following:

sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs

So I understand that the "queue" of a channel (I'm aware this terminology is not the most accurate, but for the purpose of learning myself it is what I understand about what a channel is) is of size 5 so the first 10 log messages are fine for me.

But how can be the message 6 and 13 be output their reception prior than their actual sending? How can be 7 messages sent in a row, if the channel size is 5? What am I missing from this?

  • 写回答

2条回答 默认 最新

  • dsljpwi494719 2019-05-28 13:56
    关注

    Goroutines run concurrently, therefore they also print to stdout concurrently (i.e. out-of-order). Moreover, fmt.Print APIs are buffered, so your prints are not actually prited immediately as they are called. This happens also in other languages.

    This is why you cannot derive the real concurrent execution of goroutines from the messages in stdout.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题