1. 程式人生 > >golang 讀寫鎖

golang 讀寫鎖

實現 sso error i++ lang IT 釋放 || stat

RWMutex:是基於Mutex實現的讀寫互斥鎖,一個goroutine可以持有多個讀鎖或者一個寫鎖,同一時刻只能持有讀鎖或者寫鎖

type RWMutex struct {
	w           Mutex  // 互斥鎖
	writerSem   uint32 // 寫鎖信號量
	readerSem   uint32 // 讀鎖信號量
	readerCount int32  // 讀鎖計數器   小於0時表示存在寫鎖
	readerWait  int32  // 獲取寫鎖時需要等待的讀鎖釋放數量
}

const rwmutexMaxReaders = 1 << 30   //最大讀鎖數目

// RLock locks rw for reading.
func (rw *RWMutex) RLock() {  //獲取讀鎖
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	if atomic.AddInt32(&rw.readerCount, 1) < 0 {//存在寫鎖
		// A writer is pending, wait for it.
		runtime_Semacquire(&rw.readerSem)  //等待獲取讀信號量
	}
	if race.Enabled {
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
	}
}


func (rw *RWMutex) RUnlock() {  //釋放讀鎖
	if race.Enabled {
		_ = rw.w.state
		race.ReleaseMerge(unsafe.Pointer(&rw.writerSem))
		race.Disable()
	}
	if r := atomic.AddInt32(&rw.readerCount, -1); r < 0 {  //讀鎖計數器減1
		if r+1 == 0 || r+1 == -rwmutexMaxReaders {  //沒有讀鎖
			race.Enable()
			throw("sync: RUnlock of unlocked RWMutex")
		}
		// A writer is pending.
		if atomic.AddInt32(&rw.readerWait, -1) == 0 { //讀鎖等待數目減1,如果等於0,則向寫鎖發送信號量
			// The last reader unblocks the writer.
			runtime_Semrelease(&rw.writerSem)
		}
	}
	if race.Enabled {
		race.Enable()
	}
}

func (rw *RWMutex) Lock() {
	if race.Enabled {
		_ = rw.w.state
		race.Disable()
	}
	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 { //如果存在讀鎖
		runtime_Semacquire(&rw.writerSem)
	}
	if race.Enabled {
		race.Enable()
		race.Acquire(unsafe.Pointer(&rw.readerSem))
		race.Acquire(unsafe.Pointer(&rw.writerSem))
	}
}

// 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) an RWMutex and then
// arrange for another goroutine to RUnlock (Unlock) it.
func (rw *RWMutex) Unlock() {
	if race.Enabled {
		_ = rw.w.state
		race.Release(unsafe.Pointer(&rw.readerSem))
		race.Release(unsafe.Pointer(&rw.writerSem))
		race.Disable()
	}

	// Announce to readers there is no active writer.
	r := atomic.AddInt32(&rw.readerCount, rwmutexMaxReaders) //將獲取寫鎖時減去的rwmutexMaxReaders加回去
	if r >= rwmutexMaxReaders {
		race.Enable()
		throw("sync: Unlock of unlocked RWMutex")
	}
	// Unblock blocked readers, if any.
	for i := 0; i < int(r); i++ {//換起所有掛起的讀鎖
		runtime_Semrelease(&rw.readerSem)
	}
	// Allow other writers to proceed.
	rw.w.Unlock()
	if race.Enabled {
		race.Enable()
	}
}

  

golang 讀寫鎖