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 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端