对象属性并发安全锁
2018-10-10 本文已影响45人
funcx
package main
import (
"fmt"
"sort"
"sync"
)
type A struct {
N int
}
func main() {
a := new(A)
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
P(a)
wg.Done()
}()
}
wg.Wait()
fmt.Println(haveRepeatEle(xs))
sort.Ints(xs)
fmt.Println(len(xs))
}
var xs = []int{}
var mu sync.Mutex
func P(a *A) {
mu.Lock()
i := a.N
a.N++
xs = append(xs, i)
mu.Unlock()
}
func haveRepeatEle(xs []int) bool {
for i := 0; i < len(xs); i++ {
x := xs[i]
fmt.Println("i:", i)
for j := i + 1; j < len(xs); j++ {
fmt.Println("j:", j)
if x == xs[j] {
return true
}
}
}
return false
}