Advertisement
jordancurve

Parallel processing test

Apr 20th, 2021
1,689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.88 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.         "flag"
  5.         "fmt"
  6.         "sync"
  7. )
  8.  
  9. func main() {
  10.         var nCpu int
  11.         flag.IntVar(&nCpu, "n", 0, "number of parallel procs")
  12.         flag.Parse()
  13.         fmt.Printf("nCPU=%d\n", nCpu)
  14.         wg := sync.WaitGroup{}
  15.         m := sync.Mutex{}
  16.         total := 0
  17.         for i := 0; i < nCpu; i++ {
  18.                 wg.Add(1)
  19.                 go func(i int) {
  20.                         sum := 0
  21.                         for j := 0; j < 200000000; j++ {
  22.                                 sum = (sum + 9876) * j % (2031 + i*i)
  23.                         }
  24.                         m.Lock()
  25.                         total += sum
  26.                         fmt.Printf("total(%d)=%d\n", i, sum)
  27.                         m.Unlock()
  28.                         wg.Done()
  29.                 }(i)
  30.         }
  31.         wg.Wait()
  32.         fmt.Printf("%d\n", total)
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement