Go并发之锁
作者:互联网
互斥锁
package main import ( "fmt" "sync" "time" ) //使用互斥锁计算时间 var( mu sync.Mutex x int64 wg sync.WaitGroup ) func write() { defer wg.Done() mu.Lock() x = x+1 time.Sleep(time.Millisecond*10) mu.Unlock() } func read() { defer wg.Done() mu.Lock() time.Sleep(time.Millisecond*1) mu.Unlock() } func main() { now := time.Now() for i :=0;i<10;i++{ wg.Add(1) go write() } for j :=0;j<10000;j++{ wg.Add(1) go read() } wg.Wait() fmt.Println(time.Since(now)) }
读写锁
package main import ( "fmt" "sync" "time" ) //读写锁 //使用场景,在读多写少的情况下使用,性能很高 //当写锁获取之后,读锁就会阻塞等待锁的释放,才能获取 var( mu sync.RWMutex x int64 wg sync.WaitGroup ) func writer() { defer wg.Done() mu.Lock() x = x+1 time.Sleep(time.Millisecond*10) mu.Unlock() } func read() { defer wg.Done() mu.RLock() time.Sleep(time.Millisecond*1) mu.RUnlock() } func main() { now := time.Now() for i :=0;i<10;i++{ wg.Add(1) go writer() } for j :=0;j<10000;j++{ wg.Add(1) go read() } wg.Wait() fmt.Println(time.Since(now)) }
标签:wg,Millisecond,之锁,sync,mu,并发,func,time,Go 来源: https://www.cnblogs.com/pebblecome/p/14312687.html