美文网首页
对象属性并发安全锁

对象属性并发安全锁

作者: funcx | 来源:发表于2018-10-10 22:22 被阅读45次
    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
    }
    

    相关文章

      网友评论

          本文标题:对象属性并发安全锁

          本文链接:https://www.haomeiwen.com/subject/rrzmaftx.html