func sum1(data []int) int {
s := 0
l := len(data)
for i := 0; i < l; i++ {
s += data[i]
}
return s
}
第二种方法
使用N个goroutine, 然后将N个分段的和写入N个channel中:
func sum2(data []int) int {
s := 0
l := len(data)
const 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++ {
sum += s[i]
}
out <- sum
}()
return out
}
对于一个求和的任务来说,用worker这种“模式”可能 太过麻烦, 看第三种
直接一个函数写出来:
func sum3(data []int) int {
s := 0
l := len(data)
const N = 5
seg := l / N
var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(N) // 直接加N个
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
}
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()
}
var wg sync.WaitGroup
var ch chan int32
var receiveCh chan int32
func add(){
var sum int32
sum = 0
Loop:
for {
select {
case val, ok := <-ch:
if ok {
atomic.AddInt32(&sum, val)
} else {
break Loop
}
}
}
receiveCh <- sum
wg.Done()
}
func main() {
wg.Add(3)
ch = make(chan int32)
receiveCh = make(chan int32, 2)
go func(){
for i := 1; i <= 100; i++{
n := i //避免数据竞争
ch <- int32(n)
}
close(ch)
wg.Done()
}()
go add()
go add()
wg.Wait()
close(receiveCh)
var sum int32
sum = 0
for res := range receiveCh{
sum += res
}
fmt.Println("sum:",sum)
}