drutjkpsr67393592 2017-04-06 22:39
浏览 92
已采纳

在go中使用new和channel

I found the code snippet below on a tech talk, I am a little bit confused about one thing.

Should table <- new(Ball) be placed before go player("ping", table)?
And why do we even need table <- new(Ball)? I think table := make(chan *Ball) already creates the channel. Has this something to do with deadlocks?

type Ball struct { hits int }

fun main() {
    table := make(chan *Ball)
    go player("ping", table)
    go player("pong", table)
    table <- new(Ball) // game on; toss the ball
    time.Sleep(1*time.Second)
    <-table // game over; grab the ball
}

func player(name string, table chan *Ball)
    for {
        ball := <-table
        ball.hits++
        fmt.println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        table <- ball
    }
}
  • 写回答

1条回答 默认 最新

  • dsgd4654674 2017-04-06 22:49
    关注

    The <- operator is what places something in the channel, or takes it out. The side it's on shows you if it's being placed in, or taken out. Because the channel doesn't have a size it cannot actually "hold" and item, it makes the go funcs block until there is something put in the channel. Both sides (insert and remove) block on a channel with no size, so if you try to insert something when there is no receiver, it blocks until there is one. In this specific code, the player func then removes it <- table and places it back in table <-.

    As to your question regarding moving table <- new(Ball). If you try to send the ball without a receiver, main blocks waiting for something to take the ball. A channel without a size is more like "handing" off objects because there is no storage involved. If, instead, it was created with a buffer size e.g. table := make(chan *Ball, 1), then it only blocks (the same as before) when it already has 1 item in it. So if you created it with a buffer of one, but tried to place 2 balls in it before the go funcs, it would deadlock same as before.

    https://play.golang.org/p/zrN0D8IYnn

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。