Apparently, I don't understand channels

xuanbao · · 561 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Can someone please help me figure this out? It must be something incredibly simple that I&#39;m missing.</p> <p><a href="http://play.golang.org/p/CZvn0eynfh">http://play.golang.org/p/CZvn0eynfh</a></p> <p>The program I&#39;m working on is more complicated but I managed to reduce the problem in a small mock up.</p> <p>Basically it looks like the go routine that receives from the channel is getting the same thing over and over again. Why is this? I would think when ever it receives, that item would be removed. Is a channel not a queue? Note when you make the receiver sleep for one second, it behaves as it should. Also changing the buffer size affects behavior pretty drastically as well.</p> <hr/>**评论:**<br/><br/>lacikawiz: <pre><p>The problem is not with the channels!</p> <p>You are using a pointer in the channel and then keep changing the value of the memory location where the pointer points to. So the result will be random because it all depends on when the receiver looks at it.</p> <p>Here&#39;s the fixed up version that works as expected: <a href="http://play.golang.org/p/6r6d69KRk-">http://play.golang.org/p/6r6d69KRk-</a></p></pre>washtubs: <pre><p>Nail on the head. Thanks, I see it now.</p></pre>hipone: <pre><p>fix&#39;d formatting <a href="https://play.golang.org/p/y20a0iIPBK" rel="nofollow">https://play.golang.org/p/y20a0iIPBK</a></p></pre>pierrrre: <pre><p>&#34;t&#34; is only initialized once and updated multiple times. There is a race condition. Try running your code with &#34;-race&#34; flag.</p></pre>washtubs: <pre><p>Ok, this is really cool. I need to start perusing the go help docs.</p></pre>anoland: <pre><p>I had sort of a mini epiphany the other day. We all know channels are a <em>type</em>. I&#39;ve always thought of them as a <em>communication</em> type since that is how they are documented. What I realized is that it is more accurate to think of them as a steam instead. I am going to go back and look at the examples with this new frame of reference.</p></pre>washtubs: <pre><p>Yeah, true. I mean, if you think about it, channels are not a lot more than syntactic sugar for a synchronized queue/stream, structurally at least. But it&#39;s also definitely a communication type. They really are not meant to be used in single threaded contexts (though, it is possible, I just checked). For example, if you enqueue when it&#39;s full: it triggers deadlock detection. Dequeue when it&#39;s empty, same thing. A proper queue would just tell you if it&#39;s full or empty in an error var and let you handle it.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

561 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传