1. 如何使用Channel模拟锁
type Test struct {
count int
g sync.Mutex
}
func (t *Test) add() {
t.mutex.Lock()
defer t.mutex.Unlock()
t.count++
}
func (t *Test) reduce() {
t.mutex.Lock()
defer t.mutex.Unlock()
t.count--
}func main() {
var t = &Test{}
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 100000; i++ {
t.add()
}
}()
go func() {
defer wg.Done()
for i := 0; i < 100000; i++ {
t.reduce()
}
}()
wg.Wait()
fmt.Println(t.count)
}最后更新于