互斥锁

同一时刻只有一个携程在操作

package mainimport ("fmt""math/rand""sync""time"
)
//互斥锁
var lock sync.Mutexfunc testMap() {var a map[int]inta = make(map[int]int, 5)a[8] = 10a[3] = 10a[2] = 10a[1] = 10for 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 mainimport ("fmt""math/rand""sync""time"
)//读写锁
var rwLock sync.RWMutexfunc testRWLock() {var a map[int]inta = make(map[int]int, 5)a[8] = 10a[3] = 10a[2] = 10a[1] = 10a[18] = 10for 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 mainimport ("fmt""math/rand""sync""sync/atomic""time"
)//读写锁
var rwLock sync.RWMutex
var lock sync.Mutexfunc testRWLock() {var a map[int]inta = make(map[int]int, 5)var count int32a[8] = 10a[3] = 10a[2] = 10a[1] = 10a[18] = 10for 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()//读多写少的时候,用读写锁
}