Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the Go statement execute in parallel?

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

What I'm doing wrong?

like image 395
Odomontois Avatar asked Jun 04 '11 07:06

Odomontois


1 Answers

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:

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.

like image 93
Nicholas Knight Avatar answered Nov 12 '22 23:11

Nicholas Knight