dragon0118 2018-07-31 12:57
浏览 9
已采纳

入门教程:频道和缓冲频道

Why does not the channel c buffered out when the second value is sent via another go routine and the first value sent isn't received?

package main
import "fmt"

func sum(s []int, c chan int) {
    sum := 0
    for _, v := range s {
        sum += v
    }
    c <- sum // send sum to c   
}

func main() {
    s := []int{7, 2, 8, -9, 4, 0}
    c := make(chan int)
    go sum(s[:len(s)/2], c)
    go sum(s[len(s)/2:], c)
    x, y :=  <-c ,<-c// receive from c
    fmt.Println(x,y ,x+y)
}

What I was expecting is an error-

fatal error: all goroutines are asleep - deadlock!

This occurs when there is a block when the buffer is full. Since channel c has size 1, sending the second value should have given the above error.

What is happening in above code ?

  • 写回答

1条回答 默认 最新

  • dongtuota3633 2018-07-31 18:31
    关注

    Just because a write can’t succeed immediately, you won’t get the “deadlock” error so long as there’s some other goroutine that can run.

    Let’s imagine a scheduling model where a go function immediately starts the goroutine and makes as much forward progress as it can before yielding to someone else. Then this will happen:

    1. The program will call sum() for the first half of the list, calculate the sum, and try to write it to the channel, but since there is no listener, it will block.
    2. The program will call sum() for the second half of the list, calculate the sum, and try to write it to the channel, but since there is no listener, it will block.
    3. main() will try to read from the channel, wakes up one of the previous goroutines, and gets the value from it.
    4. main() will try to read from the channel, wakes up the other blocked goroutine, and gets the value from it.
    5. Nobody’s blocked on channel input or output any more and all of the goroutines (including main()) can run to completion.

    You can do the same exercise if you pretend go just schedules something in the background and continues running the main goroutine. The important thing is that as soon as there’s a paired read and write on the same channel, both will proceed.

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

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应