Golang網課-比較互斥鎖與讀寫互斥鎖的耗時
阿新 • • 發佈:2021-07-22
一、讀寫鎖(hello.go)
package main import ( "fmt" "sync" "time" ) var ( x int64 wg sync.WaitGroup rwlck sync.RWMutex //讀寫鎖型別變數 ) func write() { defer wg.Done() rwlck.Lock() //寫鎖 x = x + 1 time.Sleep(time.Millisecond * 10) //寫操作:10ms rwlck.Unlock() //解寫鎖 } func read() { defer wg.Done() rwlck.RLock() //讀鎖 time.Sleep(time.Millisecond) //讀操作:1ms rwlck.RUnlock() //解讀鎖 } func main() { start := time.Now() for i := 0; i < 10; i++ { wg.Add(1) go write() } for i := 0; i < 100; i++ { wg.Add(1) go read() } end := time.Now() fmt.Println(end.Sub(start)) //平均耗時約 0.5 ms }
二、互斥鎖(world.go)
package main import ( "fmt" "sync" "time" ) var ( x int64 wg sync.WaitGroup lck sync.Mutex ) func write() { defer wg.Done() lck.Lock() //加互斥鎖 x = x + 1time.Sleep(time.Millisecond * 10) //寫操作耗時 10 毫秒 lck.Unlock() //解鎖 } func read() { defer wg.Done() lck.Lock() time.Sleep(time.Millisecond) //讀操作耗時 1 毫秒 lck.Unlock() } func main() { start := time.Now() for i := 0; i < 10; i++ { wg.Add(1) go write() } for i := 0; i < 100; i++ { wg.Add(1) go read() } wg.Wait() end := time.Now() fmt.Println(end.Sub(start)) //平均耗時約 1.75 s }
可以看到,相比於簡單的加入互斥鎖,讀寫鎖擁有更高的速度與效能優勢