<p>Can someone please help me figure this out? It must be something incredibly simple that I'm missing.</p>
<p><a href="http://play.golang.org/p/CZvn0eynfh">http://play.golang.org/p/CZvn0eynfh</a></p>
<p>The program I'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'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'd formatting <a href="https://play.golang.org/p/y20a0iIPBK" rel="nofollow">https://play.golang.org/p/y20a0iIPBK</a></p></pre>pierrrre: <pre><p>"t" is only initialized once and updated multiple times.
There is a race condition.
Try running your code with "-race" 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'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'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's full: it triggers deadlock detection. Dequeue when it's empty, same thing. A proper queue would just tell you if it's full or empty in an error var and let you handle it.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传