github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/sync/rw_mutex.go (about)

     1  // Copyright 2023 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package syncutils
     4  
     5  import (
     6  	"sync"
     7  )
     8  
     9  type RWMutex struct {
    10  	lockers      []*sync.RWMutex
    11  	countLockers int
    12  }
    13  
    14  func NewRWMutex(count int) *RWMutex {
    15  	if count <= 0 {
    16  		count = 1
    17  	}
    18  
    19  	var lockers = []*sync.RWMutex{}
    20  	for i := 0; i < count; i++ {
    21  		lockers = append(lockers, &sync.RWMutex{})
    22  	}
    23  
    24  	return &RWMutex{
    25  		lockers:      lockers,
    26  		countLockers: len(lockers),
    27  	}
    28  }
    29  
    30  func (this *RWMutex) Lock(index int) {
    31  	this.lockers[index%this.countLockers].Lock()
    32  }
    33  
    34  func (this *RWMutex) Unlock(index int) {
    35  	this.lockers[index%this.countLockers].Unlock()
    36  }
    37  
    38  func (this *RWMutex) RLock(index int) {
    39  	this.lockers[index%this.countLockers].RLock()
    40  }
    41  
    42  func (this *RWMutex) RUnlock(index int) {
    43  	this.lockers[index%this.countLockers].RUnlock()
    44  }
    45  
    46  func (this *RWMutex) TryLock(index int) bool {
    47  	return this.lockers[index%this.countLockers].TryLock()
    48  }
    49  
    50  func (this *RWMutex) TryRLock(index int) bool {
    51  	return this.lockers[index%this.countLockers].TryRLock()
    52  }
    53  
    54  func (this *RWMutex) RWMutex(index int) *sync.RWMutex {
    55  	return this.lockers[index%this.countLockers]
    56  }