为什么 Go 语句不并行执行? [英] Why doesn't the Go statement execute in parallel?

查看:24
本文介绍了为什么 Go 语句不并行执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 VirtualBoxed Ubuntu 11.4 上测试此 Go 代码

I'm testing this Go code on my VirtualBoxed Ubuntu 11.4

package main

import ("fmt";"time";"big")
var c chan *big.Int

func sum( start,stop,step int64) {
    bigStop := big.NewInt(stop)
    bigStep := big.NewInt(step)
    bigSum  := big.NewInt(0)
    for i := big.NewInt(start);i.Cmp(bigStop)<0 ;i.Add(i,bigStep){
        bigSum.Add(bigSum,i)
    }
    c<-bigSum           
}

func main() {
    s := big.NewInt( 0 )
    n := time.Nanoseconds()

    step := int64(4)
    c = make( chan *big.Int , int(step))
    stop := int64(100000000)
    for j:=int64(0);j<step;j++{
        go sum(j,stop,step)     
    }
    for j:=int64(0);j<step;j++{
        s.Add(s,<-c)
    }
    n = time.Nanoseconds() - n
    fmt.Println(s,float64(n)/1000000000.)
}

Ubuntu 可以访问我所有的 4 个内核.我通过同时运行多个可执行文件和系统监视器来检查这一点.但是当我尝试运行这段代码时,它只使用了一个内核,并没有从并行处理中获得任何好处.

Ubuntu has access to all my 4 cores. I checked this with simultaneous run of several executables and System Monitor. But when I'm trying to run this code, it's using only one core and is not gaining any profit of parallel processing.

我做错了什么?

推荐答案

您可能需要查看 Go FAQ 的并发部分,特别是这两个问题,并找出哪些(如果不是两者)适用于您的情况:

You probably need to review the Concurrency section of the Go FAQ, specifically these two questions, and work out which (if not both) apply to your case:

为什么我的多协程程序没有使用多个 CPU?

必须设置GOMAXPROCS shell环境变量或使用类似名称的函数运行时包允许运行时支持使用多个操作系统线程.

You must set the GOMAXPROCS shell environment variable or use the similarly-named function of the runtime package to allow the run-time support to utilize more than one OS thread.

执行并行计算的程序应该受益于 GOMAXPROCS 的增加.但是,请注意并发不是并行.

Programs that perform parallel computation should benefit from an increase in GOMAXPROCS. However, be aware that concurrency is not parallelism.

为什么使用 GOMAXPROCS > 1有时会使我的程序变慢?

这取决于你的性质程序.包含多个程序花费大量时间的 goroutine在渠道上交流将体验性能下降使用多个操作系统线程时.这是因为重要的涉及的上下文切换惩罚在线程之间发送数据.

It depends on the nature of your program. Programs that contain several goroutines that spend a lot of time communicating on channels will experience performance degradation when using multiple OS threads. This is because of the significant context-switching penalty involved in sending data between threads.

Go 的 goroutine 调度器不像好,因为它需要.未来,它应承认此类情况并优化其对操作系统线程的使用.为了现在,GOMAXPROCS 应该设置在每个应用程序的基础.

Go's goroutine scheduler is not as good as it needs to be. In future, it should recognize such cases and optimize its use of OS threads. For now, GOMAXPROCS should be set on a per-application basis.

有关此主题的更多详细信息,请参阅题为并发不是并行的演讲.

For more detail on this topic see the talk entitled Concurrency is not Parallelism.

这篇关于为什么 Go 语句不并行执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆