dongmacuo1193 2019-05-22 16:40 采纳率: 0%
浏览 16
已采纳

进入频道准备

I am trying to understand channels in Go. I have read that by default sends and receives block until both the sender and receiver are ready. But how do we figure out readyness of sender and receiver.

For example in the following code

package main

import "fmt"

func main() {
    ch := make(chan int)
    ch <- 1

    fmt.Println(<-ch)
}

The program will get stuck on the channel send operation waiting forever for someone to read the value. Even though we have a receive operation in println statement it ends up in a deadlock.

But for the following program

package main

import "fmt"

func main() {
    ch := make(chan int)

    go func () {
        ch <- 1
    }()

    fmt.Println(<-ch)
}

The integer is passed successfully from go routine to main program. What made this program work? Why second works but first do not? Is go routine causing some difference?

  • 写回答

2条回答 默认 最新

  • douli7841 2019-05-22 16:46
    关注

    Let's step through the first program:

    // My notes here
    ch := make(chan int)  // make a new int channel
    ch <- 1               // block until we can send to that channel
                          // keep blocking
                          // keep blocking
                          // still waiting for a receiver
                          // no reason to stop blocking yet...
    
    // this line is never reached, because it blocks above forever.
    fmt.Println(<-ch)
    

    The second program splits the send off into its own line of execution, so now we have:

    ch := make(chan int)  // make a new int channel
    
    go func () {          // start a new line of execution
        ch <- 1           // block this second execution thread until we can send to that channel
    }()
    
    fmt.Println(<-ch)     // block the main line of execution until we can read from that channel
    

    Since those two lines of execution can work independently, the main line can get down to fmt.Println and try and receive from the channel. The second thread will wait to send until it has.

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

报告相同问题?

悬赏问题

  • ¥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代码移植没反应