我正在我的 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/