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