dpcj40970 2013-06-02 18:42
浏览 134

了解Go中通道执行的顺序

Note: In this question I compare two versions of code and try to understand why they produce different output. Links to running examples of the two versions on play.golang.org are FIG1 and FIG2.


I'm working through the Go Concurrency Patterns slides that Rob Pike presented at Google I/O 2012 and the example on Sequencing is a bit confusing. On Slide 29 there's an example of how to restore sequencing after multiplexing. In short, messages from multiple channels are multiplexed into a single channel and each Message structure shares a channel called "waitForIt". This channel is meant to ensure that the service that provides the messages (in the referenced example the boring service) and the client of the service are in sequence. I don't understand why, in order to have a sequencing of A-B-A-B-A-B, the client must send 2 waits over the waitForIt channel:

FIG1

for i := 0; i < 10; i++ {
    msg1 := <-c
    fmt.Printf("%s
", msg1.str)
    msg2 := <-c
    fmt.Printf("%s
", msg2.str)
    msg1.wait <- true
    msg2.wait <- true  /* why is this second wait necessary? */
}

Why are two waits necessary if the Message struct is sharing the same channel? Shouldn't a single <-wait be sufficient, i.e.

FIG2

for i := 0; i < 10; i++ {
    msg1 := <-c
    fmt.Printf("%s
", msg1.str)
    msg2 := <-c
    fmt.Printf("%s
", msg2.str)
    msg1.wait <- true
}

Yet when a single wait is used, Message 1 is repeated twice at beginning of the output and then the sequencing A-B-A-B... ensues, so that what's output is:

Message 1: Iteration 0
Message 2: Iteration 0
Message 1: Iteration 1 // Message 1 is repeated twice
Message 1: Iteration 2 // Here's the repetition
Message 2: Iteration 1
Message 1: Iteration 3
Message 2: Iteration 2
Message 1: Iteration 4
Message 2: Iteration 3
Message 1: Iteration 5

When there's two sends into the wait variable, as in FIG1, the sequencing is A-B-A-B... from the beginning:

Message 1: Iteration 0
Message 2: Iteration 0
Message 1: Iteration 1
Message 2: Iteration 1
Message 1: Iteration 2
Message 2: Iteration 2
Message 1: Iteration 3
Message 2: Iteration 3
Message 1: Iteration 4
Message 2: Iteration 4

Why is the second send into wait on the same channel required for a correct sequence?

  • 写回答

2条回答 默认 最新

  • douwen9345 2013-06-02 19:42
    关注

    The sequencing examples above are incorrect. The correct examples can be found here.

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?