drtj40036 2018-01-24 07:16
浏览 37
已采纳

具有无缓冲通道的Golang例程

I am reading the book Go in action.

This is how the unbuffered channel are described:

An unbuffered channel is a channel with no capacity to hold any value before it’s received. These types of channels require both a sending and receiving goroutine to be ready at the same instant before any send or receive operation can complete. If the two goroutines aren’t ready at the same instant, the channel makes the goroutine that performs its respective send or receive operation first wait. Synchronization is inherent in the interaction between the send and receive on the channel. One can’t happenwithout the other.

The book use the following figure to illustrate the unbuffered channel:

enter image description here

So I just wonder how about if there are three or more goroutine which share the same channel?

For example, three goroutine GA GB GC share the same channel c

Now once GA send message through c, how do we make sure that both GB and GC will receive the message? Since as the book said:

These types of channels require both a sending and receiving goroutine to be ready at the same instant

Which means when two goroutine are exchanging the message, the third must lost the message.

Is this the right way goroutine run?

  • 写回答

4条回答 默认 最新

  • douzhi7754 2018-01-24 09:01
    关注

    A message sent through a channel is delivered to exactly one receiving goroutine.

    Assuming you have three goroutines, one sending and two receiving, the sending goroutine needs to send two messages for both the receiving goroutines to unblock, like this:

    var c = make(chan int)
    
    go func() { fmt.Printf("got %d
    ", <-c) }()
    go func() { fmt.Printf("got %d
    ", <-c) }()
    
    c <- 1
    c <- 2
    

    Also notice that this also requires the receiving goroutines to read exactly one message each. If they were to do it in a loop, one of them might receive both messages and the other none.

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

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据