dragon87836215 2017-06-11 05:00
浏览 133
已采纳

我可以在go中使用make(chan someStruct)吗?

for example:

type name struct {
    name string
    age int
}

func main() {
      c := make(chan name)

      c <- name{"sfsaf", 1}
      a, b := <- c

      close(c)
}

The result:

fatal error: all goroutines are asleep - deadlock!

I want to pass values through channel. What should I do?

  • 写回答

1条回答 默认 最新

  • douxie2023 2017-06-11 05:39
    关注

    Yes you can pass structs. But that's not the problem in your OP.

    You sent a value on a channel, when there was no receiver ready to receive. That is what caused your deadlock.

    Channels expect the receiver to be blocking, waiting for the sender. This is done with Goroutines.

    Therefore, wrap your sender in a goroutine, which will not execute right away.

    package main
    
    import (
        "fmt"
    )
    
    type name struct {
        name string
        age  int
    }
    
    func main() {
        c := make(chan name)
    
        go func() {
            c <- name{"sfsaf", 1}
            close(c)
        }()
    
        for n := range c {
            fmt.Println(n)
        }
    
        fmt.Println("channel was closed (all done!).")
    }
    

    See it in the playground: https://play.golang.org/p/uaSuCaB4Ms

    This works because the sender's goroutine is not executing yet. Not until the current goroutine executing gets blocked.

    And we get blocked on the for n := range c loop. This is the receiver, sitting and waiting for values. (It is a common pattern to use the for loop to iterate over channel values as it will sit and block, waiting for values).

    So now that we are blocked waiting to receive values in the for loop, the inline gorouting will now execute, to send our value on the channel.

    In addition, we follow safe practices and tidy up after ourselves and close(c) the channel, signalling the for loop or select statement that there will be no more values sent. The sender always closes, never the receiver. This is the pattern the for range loop uses to exit the for loop, and continue executing the rest of your code.


    As a side note, you did well by passing the value of the struct - not a pointer.

    If you passed a pointer, you'd have to implement some mutex lock around the object to prevent a R/W panic.

    Do not communicate by sharing memory; instead, share memory by communicating.

    Stick to passing values, not pointers, around your channels and goroutines and reap the benefits.

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

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?