multicore - 为什么 Go 语句不并行执行?

标签 multicore go parallel-processing

我正在我的 VirtualBoxed Ubuntu 11.4 上测试这段 Go 代码

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 个内核。我通过同时运行多个可执行文件和系统监视器来检查这一点。 但是当我尝试运行这段代码时,它只使用一个内核,并没有从并行处理中获得任何好处。

我做错了什么?

最佳答案

您可能需要查看 Concurrency section of the Go FAQ ,特别是这两个问题,并找出哪个(如果不是两个)适用于您的情况:

Why doesn't my multi-goroutine program use multiple CPUs?

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.

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

Why does using GOMAXPROCS > 1 sometimes make my program slower?

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'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.

关于multicore - 为什么 Go 语句不并行执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6235317/

相关文章:

java - 带有 native 代码的多核 Java 程序

visual-studio-2008 - Multiproc 在 VS2008 中构建

Tomcat SOLR 多核设置

php - 如何防止 Upstart 杀死守护进程的子进程?

c# - 循环枚举器的 PLINQ 迭代导致死锁

C++ 并行化库 : OpenMP vs. 线程构建 block

go - 为什么每个 URL 请求都会提供此服务?

sql-server - sql statement.exec错误:mssql:'?'附近的语法不正确

testing - 如何在 Go 测试中测试泄漏连接?

c++ - C++中的多线程图像处理