What is the purpose of runtime.Gosched() in this counter?

polaris · · 723 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Here is some code that I found online doing concurrent counting</p> <pre><code>package main import &#34;fmt&#34; import &#34;time&#34; import &#34;sync/atomic&#34; import &#34;runtime&#34; func main() { var ops uint64 = 0 for i := 0; i &lt; 50; i++ { go func() { for { atomic.AddUint64(&amp;ops, 1) runtime.Gosched() } }() } time.Sleep(time.Second) opsFinal := atomic.LoadUint64(&amp;ops) fmt.Println(&#34;ops:&#34;, opsFinal) } </code></pre> <p>I know that <code>runtime.Gosched()</code> switch between contexts, but why do we need to switch context when we have multiple threads?</p> <p>Is <code>runtime.Gosched()</code> necessary?</p> <hr/>**评论:**<br/><br/>alexwhoizzle: <pre><p><a href="https://github.com/golang/go/issues/11462" rel="nofollow">https://github.com/golang/go/issues/11462</a></p> <p>It&#39;s necessary only when you are running in tight for loops with no preemption points, but still want the scheduler to perform normally. </p> <p>EDIT: also see <a href="https://golang.org/doc/go1.2#preemption" rel="nofollow">https://golang.org/doc/go1.2#preemption</a></p></pre>bgeyts667: <pre><blockquote> <p>I know that runtime.Gosched() switch between contexts, but why do we need to switch context when we have multiple threads?</p> </blockquote> <p>We usually have less threads than goroutines. Therefore, Go scheduler switches every thread to run different goroutine from time to time. </p> <p>If a goroutine never does I/O or other blocking calls, it will lock the thread it&#39;s running on only for itself and never allow other goroutines to use it. Gosched() is used to force scheduler update in such cases.</p> <p>In the example every atomic counter will lock its thread if you don&#39;t put Gosched() in there. First N of the counters will lock entire thread pool of Go runtime and stop other gorouting from running.</p></pre>adonovan76: <pre><p><code>runtime.Gosched</code> is massively overused in Go tutorials. You almost never need it in practice.</p></pre>

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

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