Why can you reused channel?

polaris · · 461 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Here is a code snippet from the <a href="https://tour.golang.org/concurrency/2" rel="nofollow">official tutorial</a></p> <pre><code>package main import &#34;fmt&#34; func sum(s []int, c chan int) { sum := 0 for _, v := range s { sum += v } c &lt;- sum // send sum to c } func main() { s := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) x, y := &lt;-c, &lt;-c // receive from c fmt.Println(x, y, x+y) } </code></pre> <p>since we are doing the calculation in parallel, and each thread save its result into the same channel, doesn&#39;t this screw up the data?</p> <hr/>**评论:**<br/><br/>barsonme: <pre><blockquote> <p>since we are doing the calculation in parallel, and each thread save its result into the same channel, doesn&#39;t this screw up the data?</p> </blockquote> <p>Nope. Channels are essentially a thread-safe, FIFO queue.</p> <p>Internally, channels use locks that prevent data races when they [the channels] are used concurrently.</p></pre>Malangelus: <pre><p>I&#39;m a total novice in go, and my only experience has been writing a few packages to be used as the building blocks for making webapps comprised of distributed microservices, but my understanding of that code is that each go routine is summing half of the values, and returning that sum, and then each of those sums is assigned to a separate variable, X and Y. It&#39;s fine to do because the go routines are not touching the same values, and you don&#39;t care about which order the values are calculated and returned since you&#39;re just distributing the task of summing. I do not have a concrete understanding of go routines so if I&#39;m wrong about that then I would be thrilled if someone would correct me.</p></pre>

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

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