<p>Here is some code that I found online doing concurrent counting</p>
<pre><code>package main
import "fmt"
import "time"
import "sync/atomic"
import "runtime"
func main() {
var ops uint64 = 0
for i := 0; i < 50; i++ {
go func() {
for {
atomic.AddUint64(&ops, 1)
runtime.Gosched()
}
}()
}
time.Sleep(time.Second)
opsFinal := atomic.LoadUint64(&ops)
fmt.Println("ops:", 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'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'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'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传