【Golang1.20源码阅读】sync/rwmutex.go

// 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"
)

// 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.
// runtime/rwmutex.go中有一个修改过的文件副本。如果你在这里做任何更改,看看是否应该在那里做。

// 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.
// RWMutex是一种读写器互斥锁。锁可以由任意数量的读取器或单个写入器持有。RWMutex的零值是一个未锁定的互斥对象。
// A RWMutex must not be copied after first use.
// RWMutex在首次使用后不得复制。
// 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.
// 如果一个goroutine持有RWMutex进行读取,而另一个gorroutine可能会调用Lock,那么在释放初始读取锁之前,任何goroutine都不应该期望能够获得读取锁。特别是,这禁止递归读取锁定。这是为了确保锁最终可用;被阻止的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.
// 在Go内存模型的术语中,对于任何n<m,第n次对Unlock的调用“同步于”第m次对Lock的调用,就像Mutex一样。
// 对于任何对RLock的调用,都存在一个n,使得第n次对Unlock的调用“在”对RLock调用之前同步,
// 而对应的对RUnlock的调用“同步在”对Lock的第n+1次调用之前。
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 atomic.Int32 // number of pending readers 挂起的读者数
	// 记录写阻塞时读者个数
	readerWait  atomic.Int32 // number of departing readers 离开中的读者个数
}

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中的atomic.AddInt32不应该提供获取发布语义,这会错误地同步竞速读取器,从而可能丢失竞速。

// RLock locks rw for reading.
// RLock锁定rw进行读取。
// 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.
// 它不应该用于递归读取锁定;被阻止的Lock调用将阻止新的读卡器获取锁。请参阅有关RWMutex类型的文档。
func (rw *RWMutex) RLock() {
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	if rw.readerCount.Add(1) < 0 {
		// A writer is pending, wait for it.
		runtime_SemacquireRWMutexR(&rw.readerSem, false, 0)
	}
	if race.Enabled {
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
	}
}

// TryRLock tries to lock rw for reading and reports whether it succeeded.
// TryRLock尝试锁定rw进行读取并报告它是否成功。
// 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.
// 请注意,虽然TryRLock的正确使用确实存在,但它们是罕见的,并且TryRLlock的使用通常是互斥体的特定使用中更深层次问题的标志。
func (rw *RWMutex) TryRLock() bool {
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	for {
		c := rw.readerCount.Load()
		if c < 0 {
			if race.Enabled {
				race.Enable()
			}
			return false
		}
		if rw.readerCount.CompareAndSwap(c, c+1) {
			if race.Enabled {
				race.Enable()
				race.Acquire(unsafe.Pointer(&rw.readerSem))
			}
			return true
		}
	}
}

// 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.
// RUnlock撤消单个RLock调用;它不会影响其他同时阅读的人。如果rw没有被锁定以便在RUnlock的条目上进行读取,那么这是一个运行时错误。
func (rw *RWMutex) RUnlock() {
	if race.Enabled {
		_ = rw.w.state
		race.ReleaseMerge(unsafe.Pointer(&rw.writerSem))
		race.Disable()
	}
	if r := rw.readerCount.Add(-1); r < 0 {
		// Outlined slow-path to allow the fast-path to be inlined 列出慢速路径以允许快速路径内联
		rw.rUnlockSlow(r)
	}
	if race.Enabled {
		race.Enable()
	}
}

func (rw *RWMutex) rUnlockSlow(r int32) {
	if r+1 == 0 || r+1 == -rwmutexMaxReaders {
		race.Enable()
		fatal("sync: RUnlock of unlocked RWMutex")
	}
	// A writer is pending. 写入程序正在挂起。
	if rw.readerWait.Add(-1) == 0 {
		// The last reader unblocks the writer. 最后一个读卡器取消阻止写入程序。
		runtime_Semrelease(&rw.writerSem, false, 1)
	}
}

// Lock locks rw for writing. Lockrw进行写入。
// If the lock is already locked for reading or writing,
// Lock blocks until the lock is available.
// 如果锁已被锁定以进行读取或写入,则lock会阻止,直到锁可用为止。
func (rw *RWMutex) Lock() {
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	// First, resolve competition with other writers. 首先,解决与其他读者的竞争。
	rw.w.Lock()
	// Announce to readers there is a pending writer. 向读者宣布有一个待定的写入程序。
	r := rw.readerCount.Add(-rwmutexMaxReaders) + rwmutexMaxReaders
	// Wait for active readers. 等待活动的读者。
	if r != 0 && rw.readerWait.Add(r) != 0 {
		runtime_SemacquireRWMutex(&rw.writerSem, false, 0)
	}
	if race.Enabled {
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
		race.Acquire(unsafe.Pointer(&rw.writerSem))
	}
}

// TryLock tries to lock rw for writing and reports whether it succeeded.
// TryLock尝试锁定rw进行写入并报告它是否成功。
// 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.
// 请注意,虽然TryLock的正确使用确实存在,但它们是罕见的,并且使用TryLock通常是互斥体的特定使用中更深层次问题的标志。
func (rw *RWMutex) TryLock() bool {
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	if !rw.w.TryLock() {
		if race.Enabled {
			race.Enable()
		}
		return false
	}
	if !rw.readerCount.CompareAndSwap(0, -rwmutexMaxReaders) {
		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
}

// Unlock unlocks rw for writing. It is a run-time error if rw is
// not locked for writing on entry to Unlock.
// Unlock解锁rw进行写入。如果rw没有被锁定以便在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.
// 与Mutex一样,锁定的RWMutex与特定的goroutine没有关联。一个goroutine可以RLock(Lock)RWMutex,然后安排另一个gorroutine来RUnlock(Unlock)它。
func (rw *RWMutex) Unlock() {
	if race.Enabled {
		_ = rw.w.state
		race.Release(unsafe.Pointer(&rw.readerSem))
		race.Disable()
	}

	// Announce to readers there is no active writer. 向读者宣布没有活动的写入程序。
	r := rw.readerCount.Add(rwmutexMaxReaders)
	if r >= 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.
//RLocker返回一个Locker接口,该接口通过调用rw.RLock和rw.RUnlock来实现Lock和Unlock方法。
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() }

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/132429963
今日推荐