同步之sync.RWMutex读写锁

同步——sync.RWMutex读写锁ui

RWMutex是一个读写锁,该锁能够加多个读锁或者一个写锁,其常常用于读次数远远多于写次数的场景。code

func (rw *RWMutex) RLock() 
func (*RWMutex) RUnlock // 读解锁

读锁,写锁和读锁互斥,当只有读锁或者没有写锁时,能够加载读锁,读锁能够加载多个,因此适用于“读多写少”的场景ci

func (rw *RWMutex) Lock()
func (*RWMutex) Unlock // 写解锁

写锁,若是在添加写锁以前已经有其余的读锁和写锁,则lock就会阻塞直到该锁可用,为确保该锁最终可用,已阻塞的 Lock 调用会从得到的锁中排除新的读取器,即写锁权限高于读锁,有写锁时优先进行写锁定同步

和Java中的 ReentrantReadWriteLock 都实现类似的功能。it

下面用Go的读写锁改写余额操做的例子,io

import (
	"sync"
)

var (
	mu      sync.RWMutex // guards balance
	balance int
)

// 使用读锁保护对变量的读取
func Balance() int {
	mu.RLock()
	defer mu.RUnlock()
	b := balance
	return b
}

func Withdraw(amount int) bool {
	mu.Lock()
	defer mu.Unlock()
	deposit(-amount)
	if balance < 0 {
		deposit(amount)
		return false // insufficient funds
	}
	return true
}

func Deposit(amount int) {
	mu.Lock()
	defer mu.Unlock()
	deposit(amount)
}

// This function requires that the lock be held.
func deposit(amount int) { balance += amount }

==========END==========function

相关文章
相关标签/搜索