互斥锁
保护临界区代码在任何时刻只会在一个goroutine中运行锁机制。
临界区
访问或修改共享资源的代码区域。
Mutex
1 2 3 4 5 6 7 8 9
| import ( "sync" )
var mu sync.Mutex
mu.Lock()
mu.Unlock()
|
example
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
| package examples
import ( "fmt" "log" "sync" )
type valueCounter struct { sync.Mutex val int32 }
func (v *valueCounter) incrValue(id string) { v.Lock() defer v.Unlock()
log.Printf("incring value: %s\n", id) v.val++ }
func increaseValueCounter(n int) int32 { vc := &valueCounter{val: 0} for i := 1; i <= n; i++ { wg.Add(1) go func(index int) { defer wg.Done() vc.incrValue(fmt.Sprintf("%d", index)) }(i) }
wg.Wait()
return vc.val }
|