jordancurve icon

Parallel processing test

jordancurve | PRO | 04/21/21 03:58:24 AM UTC | 0 ⭐ | 16643 👁️ | Never ⏰ | []
Go |

880 B

|

None

|

0 👍

/

0 👎

package main
 
import (
        "flag"
        "fmt"
        "sync"
)
 
func main() {
        var nCpu int
        flag.IntVar(&nCpu, "n", 0, "number of parallel procs")
        flag.Parse()
        fmt.Printf("nCPU=%d\n", nCpu)
        wg := sync.WaitGroup{}
        m := sync.Mutex{}
        total := 0
        for i := 0; i < nCpu; i++ {
                wg.Add(1)
                go func(i int) {
                        sum := 0
                        for j := 0; j < 200000000; j++ {
                                sum = (sum + 9876) * j % (2031 + i*i)
                        }
                        m.Lock()
                        total += sum
                        fmt.Printf("total(%d)=%d\n", i, sum)
                        m.Unlock()
                        wg.Done()
                }(i)
        }
        wg.Wait()
        fmt.Printf("%d\n", total)
}

Comments