mutex(互斥锁)
- lock()加锁,unlock()解锁
适用于读写不确定,并且只有一个读或者写的场景
例:
package main import ( "sync" "time" ) var ( l *sync.mutex i int ) func increment() { l.lock() defer l.unlock() i++ } func main() { l = new(sync.mutex) for i := 0; i < 1000; i++ { go increment() } println("i=", i) time.sleep(time.second) }
rwmutex(读写锁)
- 基于mutex 实现,lock()加写锁,unlock()解写锁,rlock()加读锁,runlock()解读锁
- 多个goroutine可以同时读,读锁只会阻止写;只能一个同时写,写锁会同时阻止读写
适用于读多写少的场景
例:
package main import ( "sync" "time" ) var ( l *sync.rwmutex i int ) func write() { println("write start") l.lock() i++ l.unlock() println("write end") } func read() { println("read start") l.rlock() time.sleep(time.millisecond * 100) println("read end, i =", i) l.runlock() } func main() { l = new(sync.rwmutex) go read() go read() go write() time.sleep(time.second) }
以上代码中,会同时启动两个读和一个写,上述代码i的值可能会出现三种情况:
- (读读)写
写锁执行在两个读锁后执行,i输出为:0, 0
- 读写读
写锁在两个读锁中间执行,i输出为:0,1
- 写(读读)
写锁在两个读锁之前执行,i输出为:1,1
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论