互斥锁
同一时刻只有一个携程在操作
package main import ( "fmt" "math/rand" "sync" "time" ) //互斥锁 var lock sync.Mutex func testMap() { var a map[int]int a = make(map[int]int, 5) a[8] = 10 a[3] = 10 a[2] = 10 a[1] = 10 for i := 0; i < 2; i++ { func(b map[int]int) { lock.Lock() b[8] = rand.Intn(100) lock.Unlock() }(a) } lock.Lock() fmt.Println(a) lock.Unlock() time.Sleep(time.Second) } func main() { //互斥锁 testMap() }
读写锁
读多写少的情况,用读写锁, 携程同时在操作读。
package main import ( "fmt" "math/rand" "sync" "time" ) //读写锁 var rwLock sync.RWMutex func testRWLock() { var a map[int]int a = make(map[int]int, 5) a[8] = 10 a[3] = 10 a[2] = 10 a[1] = 10 a[18] = 10 for i := 0; i < 2; i++ { go func(b map[int]int) { rwLock.Lock() b[8] = rand.Intn(100) rwLock.Unlock() }(a) } for i := 0; i < 100; i++ { go func(b map[int]int) { rwLock.RLock() //读锁 fmt.Println(a) rwLock.RUnlock() }(a) } time.Sleep(time.Second * 20) } func main() { testRWLock() //读多写少的时候,用读写锁 }
读写锁,互斥锁,性能比较
package main import ( "fmt" "math/rand" "sync" "sync/atomic" "time" ) //读写锁 var rwLock sync.RWMutex var lock sync.Mutex func testRWLock() { var a map[int]int a = make(map[int]int, 5) var count int32 a[8] = 10 a[3] = 10 a[2] = 10 a[1] = 10 a[18] = 10 for i := 0; i < 2; i++ { go func(b map[int]int) { //rwLock.Lock() //读写锁的代码 lock.Lock() //互斥锁的代码 b[8] = rand.Intn(100) time.Sleep(10 * time.Microsecond) //微妙 //rwLock.Unlock() lock.Unlock() }(a) } for i := 0; i < 100; i++ { go func(b map[int]int) { for { //rwLock.RLock() //读写锁的代码 lock.Lock() time.Sleep(time.Millisecond) //rwLock.RUnlock() lock.Unlock() atomic.AddInt32(&count, 1) } }(a) } time.Sleep(time.Second * 20) fmt.Println(atomic.LoadInt32(&count)) } func main() { //互斥锁 testRWLock() //读多写少的时候,用读写锁 }
有疑问加站长微信联系(非本文作者)