<p>Hello everyone,</p>
<p>I'm new to Golang, and have been going through <strong>A Tour of Go</strong>. I'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'm thinking about the concept of concurrency the right way, and would like your feedback on the way I'm explaining it (to make sure I'm not cementing a wrong notion in my head).</p>
<p>Here's a simple program that greets you 3 times (and sleeps 2 seconds before each greeting):</p>
<pre><code>package main
import(
"fmt"
"time"
)
func greeting(msg string) string {
time.Sleep(2 * time.Second)
return msg
}
func main() {
fmt.Println(time.Now())
fmt.Println(greeting("hey"), greeting("hello"), greeting("hola"))
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't have to run linearly. Function calls can happen simultaneously. So I "optimized" 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(
"fmt"
"time"
)
func greeting(msg string, c chan string) {
time.Sleep(2 * time.Second)
c <- msg
}
func main() {
fmt.Println(time.Now())
c := make(chan string)
go greeting("hey", c)
go greeting("hello", c)
go greeting("hola", c)
t, u, v := <-c, <-c, <-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't actually use channels, I wouldn't be able to ensure that all my greeting functions get called and appear on the screen (since the main function's implicit goroutine could finish before they do).</p>
<p>Is the way I'm approaching this and describing the problem (although probably stupidly over-simplified) seem about right?</p>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传