两把互斥锁实现waitGroup功能
2021-01-23 本文已影响0人
funcx
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() {}()
}
}