var outside/within function behaviour

blov · · 615 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;ve been writing up some small applications and going through the go book at the same time and I&#39;ve started to look at goroutines. </p> <p>I&#39;m using <code>sync.WaitGroup</code> to wait for all routines to finish, but this is where it goes &#34;wrong&#34;.</p> <p><a href="https://gist.github.com/anonymous/12e294e7faf2d3a909d7" rel="nofollow">This script</a> gives me an error:</p> <pre><code>fatal error: all goroutines are asleep - deadlock! goroutine 1 [semacquire]: sync.(*WaitGroup).Wait(0x2081a0020) /usr/local/Cellar/go/1.4.2/libexec/src/sync/waitgroup.go:132 +0x169 main.main() /Users/gist/go/test.go:18 +0x17b exit status 2 </code></pre> <p>Now, to my understanding this means that wg.Done() actually never gets executed, or at least doesn&#39;t do anything. (I tried with a regular wg.Done() as well without defer). The Println does get executed though, so the goroutine actually progresses.</p> <p>Now, I&#39;ve got it working by moving the wg declaration outside of the main() function, <a href="https://gist.github.com/anonymous/397e39c98ae83cd358ca" rel="nofollow">like this</a></p> <p>My question now is, why does passing WaitGroup through to the PrinLine function not act as the same as declaring it outside of main?</p> <hr/>**评论:**<br/><br/>AdmiralCornbread: <pre><p>Pass a reference to the WaitGroup into &#34;printLine&#34; instead of a copy. Right now you&#39;re making a copy, and the original is never modified when &#34;wg.Done()&#34; is executed.</p> <p><a href="http://play.golang.org/p/lz53ZOmhUs" rel="nofollow">See this version of your code</a> with this small modification to the function signature and call.</p></pre>alexwhoizzle: <pre><p>So, in your first example you declare the sync.WaitGroup in main(), but you pass a COPY of the sync.WaitGroup to the printLine() function. Calling wg.Done() in printLine() isn&#39;t calling Done() on your original WaitGroup, but instead on a COPY of your WaitGroup. To fix this your printLine() function needs to take a pointer to a sync.WaitGroup and you should pass in &amp;wg to your function. </p> <p>The reason your second example works is because the sync.WaitGroup is declared at the package level, so it can be called from both main() and your printLine() function without any problems.</p> <p>Read up on <a href="https://golang.org/doc/faq#pass_by_value" rel="nofollow">https://golang.org/doc/faq#pass_by_value</a> for more info.</p></pre>golanguser: <pre><p>That makes a lot of sense now. Thanks for the link to the pass by value, I missed that!</p></pre>

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

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