100-go-mistakes/12-optimizations/92-false-sharing/main.go
2021-12-27 15:56:17 +01:00

67 lines
840 B
Go

package main
import "sync"
type Input struct {
a int64
b int64
}
type Result1 struct {
sumA int64
sumB int64
}
func count1(inputs []Input) Result1 {
wg := sync.WaitGroup{}
wg.Add(2)
result := Result1{}
go func() {
for i := 0; i < len(inputs); i++ {
result.sumA += inputs[i].a
}
wg.Done()
}()
go func() {
for i := 0; i < len(inputs); i++ {
result.sumB += inputs[i].b
}
wg.Done()
}()
wg.Wait()
return result
}
type Result2 struct {
sumA int64
_ [56]byte
sumB int64
}
func count2(inputs []Input) Result2 {
wg := sync.WaitGroup{}
wg.Add(2)
result := Result2{}
go func() {
for i := 0; i < len(inputs); i++ {
result.sumA += inputs[i].a
}
wg.Done()
}()
go func() {
for i := 0; i < len(inputs); i++ {
result.sumB += inputs[i].b
}
wg.Done()
}()
wg.Wait()
return result
}