Mutex最佳实践
mutex 会嵌入到其他struct使用,如果嵌入的字段过多,会将Mutex放在控制的字段上面,然后使用空格将字段分隔出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package main
import ( "fmt" "sync" )
func main() { var counter Counter var wg sync.WaitGroup
for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < 10000; j++ { counter.Incr() } }() }
wg.Wait() fmt.Println(counter.Count()) }
type Counter struct { CounterType int Name string
mu sync.Mutex count uint64 }
func (c *Counter) Incr() { c.mu.Lock() c.count++ c.mu.Unlock() }
func (c *Counter) Count() uint64 { c.mu.Lock() defer c.mu.Unlock() return c.count }
|