# golang 实现并发求和

## 为了验证结果的正确性，要给出最传统的版本：

func sum1(data []int) int {
s := 0
l := len(data)
for i := 0; i < l; i++ {
s += data[i]
}
return s
}

## 第二种方法

func sum2(data []int) int 编程客栈{
s := 0
l := len(data)
www.cppcns.comconst N = 5
seg := l / N
var chs [N]<-chan int
for i := 0; i < N; i++ {
chs[i] = worker(data[i*seg : (i+1)*seg])
}
for i := 0; i < N; i++ {
s += <-chs[i]
}
return s
}
func worker(s []int) <-chan int {
out := make(chan int)
go func() {
length := len(s)
sum := 0
for i := 0; i < length; i++ {
http://www.cppcns.com   sum += s[i]
}
out <- sum
}()
return out
}

## 看第三种

f编程客栈unc sum3(data []int) int {
s := 0
l := len(data)
const N = 5
seg := l / N
var mu sync.Mutex
var wg sync.WaitGroup
for i := 0; i < N; i++ {
go func(ii int) {
tmpS := data[ii*seg : (ii+1)*seg]
ll := len(tmpS)
mu.Lock()
for i := 0; i < ll; i++ {
s += tmpS[i]
}
mu.Unlock()
wg.Done() // 一个goroutine运行完
}(i)
}
wg.Wait() // 等N个goroutine都运行完
return s
}

## 最后一种方法有data race问题

var sum4Tmp int
var sum4mu sync.Mutex
// 这个有data race问题，可以用WaitGroup改，只是提供一种思路
func sum4(data []int) int {
//s := 0
l := len(data)
const N = 5
seg := l / N
for i := 0; i < N; i++ {
go subsum4(data[i*seg : (i+1)*seg])
}
// 这里是>1，因为要排除main
// 这种方法不可靠，只是一种思路
for runtime.NumGoroutine() > 1 {
}
// go run -race sum.go会报data race问题
// main goroutine对它读
// 别的goroutine会对它写（go subsum4)
return sum4Tmp
}
func subsum4(s []int) {
length := len(s)
sum := 0
sum4mu.Lock()
for i := 0; i < length; i++ {
sum += s[i]
}
sum4Tmp = sum4Tmp + sum
defer sum4mu.Unlock()
}

## 然后用4种方法进行计算

func calcTime(f func([]int) int, arr []int, tag string) {
t1 := time.Now().UnixNano()
s := f(arr)
t2 := time.Now().UnixNano() - t1
fmt.Printf("%15s: time: %d, sum: %d\n", tag, t2, s)
}
func main() {
const MAX = 1e8 // 1亿
arr := make([]int, MAX)
for i := 0; i < MAX; i++ {
arr[i] = rand.Intn(10)
}
calcTime(sum1, arr, "for")
calcTime(sum2, arr, "worker")
cwww.cppcns.comalcTime(sum3, arr, "WaitGroup")
calcTime(sum4, arr, "NumGoroutine")
}

for: time: 61834200, sum: 450032946

worker: time: 51861100, sum: 450032946

WaitGroup: time: 153628200, sum: 450032946

NumGoroutine: time: 63791300, sum: 450032946

## 解决方案：

var wg sync.WaitGroup
var ch chan int32
var sum int32
sum = 0
Loop:
for {
select {
case val, ok := <-ch:
if ok {
} else {
break Loop
}
}
}
wg.Done()
}
func main() {
ch = make(chan int32)
go func(){
for i := 1; i <= 100; i++{
n := i //避免数据竞争
ch <- int32(n)
}
close(ch)
wg.Done()
}()
wg.Wait()
var sum int32
sum = 0