github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/lang/syncx/rwmutex.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package syncx
    16  
    17  import (
    18  	"runtime"
    19  	"sync"
    20  	"unsafe"
    21  
    22  	"github.com/bytedance/gopkg/internal/runtimex"
    23  
    24  	"golang.org/x/sys/cpu"
    25  )
    26  
    27  const (
    28  	cacheLineSize = unsafe.Sizeof(cpu.CacheLinePad{})
    29  )
    30  
    31  var (
    32  	shardsLen int
    33  )
    34  
    35  // RWMutex is a p-shard mutex, which has better performance when there's much more read than write.
    36  type RWMutex []rwMutexShard
    37  
    38  type rwMutexShard struct {
    39  	sync.RWMutex
    40  	_pad [cacheLineSize - unsafe.Sizeof(sync.RWMutex{})]byte
    41  }
    42  
    43  func init() {
    44  	shardsLen = runtime.GOMAXPROCS(0)
    45  }
    46  
    47  // NewRWMutex creates a new RWMutex.
    48  func NewRWMutex() RWMutex {
    49  	return make([]rwMutexShard, shardsLen)
    50  }
    51  
    52  func (m RWMutex) Lock() {
    53  	for shard := range m {
    54  		m[shard].Lock()
    55  	}
    56  }
    57  
    58  func (m RWMutex) Unlock() {
    59  	for shard := range m {
    60  		m[shard].Unlock()
    61  	}
    62  }
    63  
    64  func (m RWMutex) RLocker() sync.Locker {
    65  	return m[runtimex.Pid()%shardsLen].RWMutex.RLocker()
    66  }