Feed back on simple program with goroutines

xuanbao · · 474 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello everyone,</p> <p>I&#39;m new to Golang, and have been going through <strong>A Tour of Go</strong>. I&#39;m currently on the section about goroutines and channels. To help myself better understand the concept of concurrency, I made a twist on a sample program. I want to make sure I&#39;m thinking about the concept of concurrency the right way, and would like your feedback on the way I&#39;m explaining it (to make sure I&#39;m not cementing a wrong notion in my head).</p> <p>Here&#39;s a simple program that greets you 3 times (and sleeps 2 seconds before each greeting):</p> <pre><code>package main import( &#34;fmt&#34; &#34;time&#34; ) func greeting(msg string) string { time.Sleep(2 * time.Second) return msg } func main() { fmt.Println(time.Now()) fmt.Println(greeting(&#34;hey&#34;), greeting(&#34;hello&#34;), greeting(&#34;hola&#34;)) fmt.Println(time.Now()) } </code></pre> <p>So it looks like it takes about <strong>6</strong> seconds to run:</p> <pre><code>$ go run hello_nonoptimized.go 2017-09-08 14:46:32.4106001 -0400 EDT m=+0.004000000 hey hello hola 2017-09-08 14:46:38.4116001 -0400 EDT m=+6.005000000 </code></pre> <p>My understanding of <strong>goroutines</strong> and <strong>concurrency</strong> is that my program doesn&#39;t have to run linearly. Function calls can happen simultaneously. So I &#34;optimized&#34; this program so each function call will greet you after 2 seconds (like it is supposed to), but the big idea of concurrency is that function calls can happen nearly at once.</p> <pre><code>package main import( &#34;fmt&#34; &#34;time&#34; ) func greeting(msg string, c chan string) { time.Sleep(2 * time.Second) c &lt;- msg } func main() { fmt.Println(time.Now()) c := make(chan string) go greeting(&#34;hey&#34;, c) go greeting(&#34;hello&#34;, c) go greeting(&#34;hola&#34;, c) t, u, v := &lt;-c, &lt;-c, &lt;-c fmt.Println(t, u, v) fmt.Println(time.Now()) } </code></pre> <p>Now, despite each function call taking about 2 seconds, my program finishes in about a total of 2 seconds because all those calls are happening nearly simultaneously.</p> <pre><code>$ go run hello_optimized.go 2017-09-08 14:50:53.1726001 -0400 EDT m=+0.004000000 hola hey hello 2017-09-08 14:50:55.1726001 -0400 EDT m=+2.004000000 </code></pre> <p>If I didn&#39;t actually use channels, I wouldn&#39;t be able to ensure that all my greeting functions get called and appear on the screen (since the main function&#39;s implicit goroutine could finish before they do).</p> <p>Is the way I&#39;m approaching this and describing the problem (although probably stupidly over-simplified) seem about right?</p>

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

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