Go 1.19.3 sync.RWMutex原理简析

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

RWMutex 读写锁

读写锁适用于读多写少的场景。某一个时刻可以有多个goroutine同时获得读锁但只能有一个goroutine获得写锁。多个读锁锁定的时候写锁必须等待所有读锁释放后才能抢占。同理读锁须等待写锁释放后才能抢占。

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sync

import (
	"internal/race"
	"sync/atomic"
	"unsafe"
)

RWMutex 结构

RWMutex结构体维护了一个Mutex类型的m用于写操作保护同时维护了writerSem(写锁等待读取完成信号量)readerSem(读锁等待写入完成信号量)readerCount(进行中的读操作数量)readerWait(写操作被阻塞时读操作的数量)。

// There is a modified copy of this file in runtime/rwmutex.go.
// If you make any changes here, see if you should make them there.

// A RWMutex is a reader/writer mutual exclusion lock.
// The lock can be held by an arbitrary number of readers or a single writer.
// The zero value for a RWMutex is an unlocked mutex.
//
// A RWMutex must not be copied after first use.
//
// If a goroutine holds a RWMutex for reading and another goroutine might
// call Lock, no goroutine should expect to be able to acquire a read lock
// until the initial read lock is released. In particular, this prohibits
// recursive read locking. This is to ensure that the lock eventually becomes
// available; a blocked Lock call excludes new readers from acquiring the
// lock.
//
// In the terminology of the Go memory model,
// the n'th call to Unlock “synchronizes before” the m'th call to Lock
// for any n < m, just as for Mutex.
// For any call to RLock, there exists an n such that
// the n'th call to Unlock “synchronizes before” that call to RLock,
// and the corresponding call to RUnlock “synchronizes before”
// the n+1'th call to Lock.
type RWMutex struct {
	w           Mutex  // held if there are pending writers
	writerSem   uint32 // semaphore for writers to wait for completing readers
	readerSem   uint32 // semaphore for readers to wait for completing writers
	readerCount int32  // number of pending readers
	readerWait  int32  // number of departing readers
}

RLock 读锁锁定用原子操作将readerCount增加1若该值为负数则证明有写的操作在进行此时用信号量阻塞

const rwmutexMaxReaders = 1 << 30  //最大读操作数量

// Happens-before relationships are indicated to the race detector via:
// - Unlock  -> Lock:  readerSem
// - Unlock  -> RLock: readerSem
// - RUnlock -> Lock:  writerSem
//
// The methods below temporarily disable handling of race synchronization
// events in order to provide the more precise model above to the race
// detector.
//
// For example, atomic.AddInt32 in RLock should not appear to provide
// acquire-release semantics, which would incorrectly synchronize racing
// readers, thus potentially missing races.

// RLock locks rw for reading.
//
// It should not be used for recursive read locking; a blocked Lock
// call excludes new readers from acquiring the lock. See the
// documentation on the RWMutex type.
func (rw *RWMutex) RLock() {
	if race.Enabled { // race相关
		_ = rw.w.state
		race.Disable()
	}
	if atomic.AddInt32(&rw.readerCount, 1) < 0 { // 若readerCount
		// A writer is pending, wait for it.
		runtime_SemacquireMutex(&rw.readerSem, false, 0)
	}
	if race.Enabled { // race相关
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
	}
}

TryRLock尝试读锁上锁自旋若有写入操作直接返回false否则将readerCount用cas操作增加1返回true

// TryRLock tries to lock rw for reading and reports whether it succeeded.
//
// Note that while correct uses of TryRLock do exist, they are rare,
// and use of TryRLock is often a sign of a deeper problem
// in a particular use of mutexes.
func (rw *RWMutex) TryRLock() bool {
	if race.Enabled { //race相关
		_ = rw.w.state
		race.Disable()
	}
	for { //自旋
		c := atomic.LoadInt32(&rw.readerCount) //获取读操作数量
		if c < 0 { // 读操作数数 < 0, 则证明有写操作直接返回false
			if race.Enabled { // race 相关
				race.Enable()
			}
			return false
		}
		if atomic.CompareAndSwapInt32(&rw.readerCount, c, c+1) { // 原子+1
			if race.Enabled { //race相关
				race.Enable()
				race.Acquire(unsafe.Pointer(&rw.readerSem))
			}
			return true //返回true
		}
	}
}

RUnLock 读锁解锁原子操作

// RUnlock undoes a single RLock call;
// it does not affect other simultaneous readers.
// It is a run-time error if rw is not locked for reading
// on entry to RUnlock.
func (rw *RWMutex) RUnlock() {
	if race.Enabled { // race相关
		_ = rw.w.state
		race.ReleaseMerge(unsafe.Pointer(&rw.writerSem))
		race.Disable()
	}
	if r := atomic.AddInt32(&rw.readerCount, -1); r < 0 { //读操作数 -1
		// Outlined slow-path to allow the fast-path to be inlined
		rw.rUnlockSlow(r) // r < 0 证明解读锁操作调用多了。
	}
	if race.Enabled { // race相关
		race.Enable()
	}
}

func (rw *RWMutex) rUnlockSlow(r int32) {
	if r+1 == 0 || r+1 == -rwmutexMaxReaders { //解锁操作与上锁操作数量不匹配
		race.Enable()
		fatal("sync: RUnlock of unlocked RWMutex") // panic
	}
	// A writer is pending.
	if atomic.AddInt32(&rw.readerWait, -1) == 0 { // 如果读的等待数-1为0是最后一个被释放的读锁
		// The last reader unblocks the writer.
		runtime_Semrelease(&rw.writerSem, false, 1) // 释放写信号量
	}
}

Lock 写锁上锁直接调用互斥锁的Lock然后检查读操作数量若非0则等待其归零后返回

// Lock locks rw for writing.
// If the lock is already locked for reading or writing,
// Lock blocks until the lock is available.
func (rw *RWMutex) Lock() {
	if race.Enabled { // race 相关
		_ = rw.w.state
		race.Disable()
	}
	// First, resolve competition with other writers.
	rw.w.Lock() // 内置互斥锁上锁
	// Announce to readers there is a pending writer.
	r := atomic.AddInt32(&rw.readerCount, -rwmutexMaxReaders) + rwmutexMaxReaders // 读操作数量
	// Wait for active readers.
	if r != 0 && atomic.AddInt32(&rw.readerWait, r) != 0 { // 读操作数量非0等待数 + 读读操作数量非0
		runtime_SemacquireMutex(&rw.writerSem, false, 0) // 阻塞直到读操作数量为0
	}
	if race.Enabled { //race相关
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
		race.Acquire(unsafe.Pointer(&rw.writerSem))
	}
}

TryLock 尝试获取写锁先尝试调用互斥锁的TryLock而后根据读操作数量确定是否可以上锁若上锁则将读操作数量置为负的最大预定值

// TryLock tries to lock rw for writing and reports whether it succeeded.
//
// Note that while correct uses of TryLock do exist, they are rare,
// and use of TryLock is often a sign of a deeper problem
// in a particular use of mutexes.
func (rw *RWMutex) TryLock() bool {
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	if !rw.w.TryLock() { // 尝试获取互斥锁的TryLock
		if race.Enabled {
			race.Enable()
		}
		return false
	}
	if !atomic.CompareAndSwapInt32(&rw.readerCount, 0, -rwmutexMaxReaders) { //读操作数量为0则尝试置读操作数量为负的最大值代表此时有写操作并尝试解锁返回
		rw.w.Unlock()
		if race.Enabled {
			race.Enable()
		}
		return false
	}
	if race.Enabled {
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
		race.Acquire(unsafe.Pointer(&rw.writerSem))
	}
	return true //读操作数量为0则获取到了锁返回true
}

Unlock 解写锁尝试唤醒读锁

// Unlock unlocks rw for writing. It is a run-time error if rw is
// not locked for writing on entry to Unlock.
//
// As with Mutexes, a locked RWMutex is not associated with a particular
// goroutine. One goroutine may RLock (Lock) a RWMutex and then
// arrange for another goroutine to RUnlock (Unlock) it.
func (rw *RWMutex) Unlock() {
	if race.Enabled { //race相关
		_ = rw.w.state
		race.Release(unsafe.Pointer(&rw.readerSem))
		race.Disable()
	}

	// Announce to readers there is no active writer.
	r := atomic.AddInt32(&rw.readerCount, rwmutexMaxReaders) //先试图恢复readCount
	if r >= rwmutexMaxReaders { // 重复解锁解写锁的时候就会对 readerCount + rwmutexMaxReaders
		race.Enable()
		fatal("sync: Unlock of unlocked RWMutex")
	}
	// Unblock blocked readers, if any.
	for i := 0; i < int(r); i++ { // 释放读操作信号量
		runtime_Semrelease(&rw.readerSem, false, 0)
	}
	// Allow other writers to proceed.
	rw.w.Unlock() //解锁
	if race.Enabled {
		race.Enable()
	}
}

// 以下为sync包内使用的读写锁
// RLocker returns a Locker interface that implements
// the Lock and Unlock methods by calling rw.RLock and rw.RUnlock.
func (rw *RWMutex) RLocker() Locker {
	return (*rlocker)(rw)
}

type rlocker RWMutex

func (r *rlocker) Lock()   { (*RWMutex)(r).RLock() }
func (r *rlocker) Unlock() { (*RWMutex)(r).RUnlock() }
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: go