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 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类