Mutex的Lock和Unlock
package main
import (
"fmt"
"sync"
)
// Count 临界资源,mutex字段嵌入结构体
type Count struct {
CounterType int
Name string
// mutex字段一般放在临界资源的上面
sync.Mutex
Counter int
}
// Incr 加锁、解锁、自增操作
func (c *Count) Incr() {
c.Lock()
c.Counter++
c.Unlock()
}
// GetCount 获取值操作,同样加锁
func (c *Count) GetCount() int {
c.Lock()
defer c.Unlock()
return c.Counter
}
func main() {
var wg sync.WaitGroup
var count Count
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
for j := 0; j < 10000; j++ {
count.Incr()
}
}()
}
wg.Wait()
fmt.Println(count.GetCount())
}