GO 锁
不加锁
package main import ( "fmt" "sync" ) var x=0 var wg107 sync.WaitGroup func add1() { for i := 0; i < 50000; i++ { x += 1 } wg107.Done() } func test1() { wg107.Add(2) go add1() go add1() wg107.Wait() fmt.Println("Done ~", x) } func main() { test1() }
执行1:Done ~ 59534
执行2:Done ~ 50243
可以看出每次执行结果不一,原因:共有变量x,没加锁,导致可能同时获取到加1,导致只加了1次
互斥锁
package main import ( "fmt" "sync" ) var x=0 var wg107 sync.WaitGroup var lock sync.Mutex func add2() { for i := 0; i < 50000; i++ { lock.Lock() x += 1 lock.Unlock() } wg107.Done() } func test2() { wg107.Add(2) go add2() go add2() wg107.Wait() fmt.Println("Done ~", x) } func main() { test2() }
读写互斥锁
package main import ( "fmt" "sync" "time" ) var x = 0 var wg107 sync.WaitGroup var rwlock sync.RWMutex func read() { defer wg107.Done() rwlock.RLock() time.Sleep(time.Millisecond) rwlock.RUnlock() } func write() { defer wg107.Done() rwlock.Lock() time.Sleep(time.Millisecond * 10) rwlock.Unlock() } func test3() { start := time.Now() for i := 0; i < 10; i++ { wg107.Add(1) go write() } for i := 0; i < 100; i++ { wg107.Add(1) go read() } wg107.Wait() fmt.Println(time.Now().Sub(start)) } func main() { test3() }
执行:
111.770703ms