douya1061 2017-05-27 11:44
浏览 18
已采纳

为什么golang中的频道需要执行常规程序?

I am coming upto speed on channels in golang. Per its documentation,

Channels are a typed conduit through which you can send and receive values with the channel operator, <-.

I get that. I understand how it is used from examples that utilize go routines. I tried an extremely trivial example. It results in a deadlocked program. Ignoring the pointlessness of this program can you please tell me why this is deadlocked?

package main
import  "fmt"
func main() {
    c := make(chan int)
    c <- 17
    fmt.Println(<- c)
}

The referenced documentation adds that

By default, sends and receives block until the other side is ready.

OK, in the above example, the sender (the main routine) is ready to send when c <- 17 is encountered. So shouldn't that execute. Subsequently the Println should be able to drain the channel.

I realize everything works fine if c <- 17 is replaced by

go func() { c <- 17 } ()

Just trying to understand why that's necessary.

  • 写回答

2条回答 默认 最新

  • dongxiaoyan4388 2017-05-27 11:52
    关注

    By default, sends and receives block until the other side is ready.

    Exactly: since no go routine is waiting to receive, the send is blocked, and your program deadlocks. The send operation does not get skipped over because no one is waiting to receive.

    If you want to do a non-blocking send, you would use the send operator in a select statement with a default case:

    select {
    case c <- 17:
    default:
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退