Go 1.19.3 sync.RWMutex原理简析

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()
	}
}

// 返回读锁的对象
// 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() }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

metabit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值