github.com/gogf/gf/v2@v2.7.4/internal/rwmutex/rwmutex.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). 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/gogf/gf.
     6  
     7  // Package rwmutex provides switch of concurrent safety feature for sync.RWMutex.
     8  package rwmutex
     9  
    10  import (
    11  	"sync"
    12  )
    13  
    14  // RWMutex is a sync.RWMutex with a switch for concurrent safe feature.
    15  // If its attribute *sync.RWMutex is not nil, it means it's in concurrent safety usage.
    16  // Its attribute *sync.RWMutex is nil in default, which makes this struct mush lightweight.
    17  type RWMutex struct {
    18  	// Underlying mutex.
    19  	mutex *sync.RWMutex
    20  }
    21  
    22  // New creates and returns a new *RWMutex.
    23  // The parameter `safe` is used to specify whether using this mutex in concurrent safety,
    24  // which is false in default.
    25  func New(safe ...bool) *RWMutex {
    26  	mu := Create(safe...)
    27  	return &mu
    28  }
    29  
    30  // Create creates and returns a new RWMutex object.
    31  // The parameter `safe` is used to specify whether using this mutex in concurrent safety,
    32  // which is false in default.
    33  func Create(safe ...bool) RWMutex {
    34  	if len(safe) > 0 && safe[0] {
    35  		return RWMutex{
    36  			mutex: new(sync.RWMutex),
    37  		}
    38  	}
    39  	return RWMutex{}
    40  }
    41  
    42  // IsSafe checks and returns whether current mutex is in concurrent-safe usage.
    43  func (mu *RWMutex) IsSafe() bool {
    44  	return mu.mutex != nil
    45  }
    46  
    47  // Lock locks mutex for writing.
    48  // It does nothing if it is not in concurrent-safe usage.
    49  func (mu *RWMutex) Lock() {
    50  	if mu.mutex != nil {
    51  		mu.mutex.Lock()
    52  	}
    53  }
    54  
    55  // Unlock unlocks mutex for writing.
    56  // It does nothing if it is not in concurrent-safe usage.
    57  func (mu *RWMutex) Unlock() {
    58  	if mu.mutex != nil {
    59  		mu.mutex.Unlock()
    60  	}
    61  }
    62  
    63  // RLock locks mutex for reading.
    64  // It does nothing if it is not in concurrent-safe usage.
    65  func (mu *RWMutex) RLock() {
    66  	if mu.mutex != nil {
    67  		mu.mutex.RLock()
    68  	}
    69  }
    70  
    71  // RUnlock unlocks mutex for reading.
    72  // It does nothing if it is not in concurrent-safe usage.
    73  func (mu *RWMutex) RUnlock() {
    74  	if mu.mutex != nil {
    75  		mu.mutex.RUnlock()
    76  	}
    77  }