美文网首页
两把互斥锁实现waitGroup功能

两把互斥锁实现waitGroup功能

作者: funcx | 来源:发表于2021-01-23 11:59 被阅读0次
    package main
    
    import (
        "log"
        "sync"
    )
    
    type Counter struct {
        count     int
        mu1       sync.Mutex
        mu2       sync.Mutex
        needLock2 bool
    }
    
    func NewCounter(initValue int) *Counter {
        c := &Counter{count: initValue}
        if initValue != 0 {
            c.mu2.Lock()
        }
        return c
    }
    
    func (counter *Counter) Add(v int) {
        if v == 0 {
            return
        }
        counter.mu1.Lock()
        counter.count += v
        if counter.count != 0 && counter.needLock2 {
            counter.mu2.Lock()
            counter.needLock2 = false
        } else if counter.count == 0 {
            counter.mu2.Unlock()
            counter.needLock2 = true
        }
        log.Println("current value:", counter.count)
        counter.mu1.Unlock()
    }
    
    func (counter *Counter) Wait() {
        counter.mu2.Lock()
        counter.mu2.Unlock()
        log.Println("wait成功")
    }
    
    func main() {
        //counter := NewCounter(200)
        //wg := sync.WaitGroup{}
        for i := 0; i < 100; i++ {
            go func() {}()
        }
    }
    

    相关文章

      网友评论

          本文标题:两把互斥锁实现waitGroup功能

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