func TestLock() {
/*互斥锁`````````````````````````````````````````````````````````````````````````````````````````````*/
var m sync.Mutex
for i := 0; i < 3; i++ {
go func(i int) { //加锁|解锁:多个互斥锁也是阻塞的
m.Lock()
defer m.Unlock()
time.Sleep(time.Millisecond * 3000)
fmt.Println("阻塞式mutex:", i)
}(i)
}
/*读写锁`````````````````````````````````````````````````````````````````````````````````````````````*/
var rwm sync.RWMutex
for i := 0; i < 3; i++ {
go func(i int) { //读锁:并发执行,不阻塞
rwm.RLock()
defer rwm.RUnlock()
time.Sleep(time.Millisecond * 100)
fmt.Println("并发式read:", i)
}(i)
}
for i := 0; i < 3; i++ {
go func(i int) { //写锁:并发执行多写锁==有点像解并发;就是多个写锁要一个完成下一个再执行(多写锁相互阻塞)
rwm.Lock()
defer rwm.Unlock()
time.Sleep(time.Millisecond * 1000)
fmt.Println("阻塞式write:", i)
}(i)
}
time.Sleep(time.Millisecond * 15000)
}
/*互斥锁`````````````````````````````````````````````````````````````````````````````````````````````*/
var m sync.Mutex
for i := 0; i < 3; i++ {
go func(i int) { //加锁|解锁:多个互斥锁也是阻塞的
m.Lock()
defer m.Unlock()
time.Sleep(time.Millisecond * 3000)
fmt.Println("阻塞式mutex:", i)
}(i)
}
/*读写锁`````````````````````````````````````````````````````````````````````````````````````````````*/
var rwm sync.RWMutex
for i := 0; i < 3; i++ {
go func(i int) { //读锁:并发执行,不阻塞
rwm.RLock()
defer rwm.RUnlock()
time.Sleep(time.Millisecond * 100)
fmt.Println("并发式read:", i)
}(i)
}
for i := 0; i < 3; i++ {
go func(i int) { //写锁:并发执行多写锁==有点像解并发;就是多个写锁要一个完成下一个再执行(多写锁相互阻塞)
rwm.Lock()
defer rwm.Unlock()
time.Sleep(time.Millisecond * 1000)
fmt.Println("阻塞式write:", i)
}(i)
}
time.Sleep(time.Millisecond * 15000)
}