github.com/zhongdalu/gf@v1.0.0/g/internal/rwmutex/rwmutex.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  // Package rwmutex provides switch of concurrent safe feature for sync.RWMutex.
     8  package rwmutex
     9  
    10  import "sync"
    11  
    12  // RWMutex is a sync.RWMutex with a switch of concurrent safe feature.
    13  type RWMutex struct {
    14  	sync.RWMutex
    15  	safe bool
    16  }
    17  
    18  func New(unsafe ...bool) *RWMutex {
    19  	mu := new(RWMutex)
    20  	if len(unsafe) > 0 {
    21  		mu.safe = !unsafe[0]
    22  	} else {
    23  		mu.safe = true
    24  	}
    25  	return mu
    26  }
    27  
    28  func (mu *RWMutex) IsSafe() bool {
    29  	return mu.safe
    30  }
    31  
    32  func (mu *RWMutex) Lock() {
    33  	if mu.safe {
    34  		mu.RWMutex.Lock()
    35  	}
    36  }
    37  
    38  func (mu *RWMutex) Unlock() {
    39  	if mu.safe {
    40  		mu.RWMutex.Unlock()
    41  	}
    42  }
    43  
    44  func (mu *RWMutex) RLock() {
    45  	if mu.safe {
    46  		mu.RWMutex.RLock()
    47  	}
    48  }
    49  
    50  func (mu *RWMutex) RUnlock() {
    51  	if mu.safe {
    52  		mu.RWMutex.RUnlock()
    53  	}
    54  }