github.com/gogf/gf/v2@v2.7.4/internal/mutex/mutex.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 mutex provides switch of concurrent safe feature for sync.Mutex. 8 package mutex 9 10 import ( 11 "sync" 12 ) 13 14 // Mutex is a sync.Mutex with a switch for concurrent safe feature. 15 type Mutex struct { 16 // Underlying mutex. 17 mutex *sync.Mutex 18 } 19 20 // New creates and returns a new *Mutex. 21 // The parameter `safe` is used to specify whether using this mutex in concurrent safety, 22 // which is false in default. 23 func New(safe ...bool) *Mutex { 24 mu := Create(safe...) 25 return &mu 26 } 27 28 // Create creates and returns a new Mutex object. 29 // The parameter `safe` is used to specify whether using this mutex in concurrent safety, 30 // which is false in default. 31 func Create(safe ...bool) Mutex { 32 if len(safe) > 0 && safe[0] { 33 return Mutex{ 34 mutex: new(sync.Mutex), 35 } 36 } 37 return Mutex{} 38 } 39 40 // IsSafe checks and returns whether current mutex is in concurrent-safe usage. 41 func (mu *Mutex) IsSafe() bool { 42 return mu.mutex != nil 43 } 44 45 // Lock locks mutex for writing. 46 // It does nothing if it is not in concurrent-safe usage. 47 func (mu *Mutex) Lock() { 48 if mu.mutex != nil { 49 mu.mutex.Lock() 50 } 51 } 52 53 // Unlock unlocks mutex for writing. 54 // It does nothing if it is not in concurrent-safe usage. 55 func (mu *Mutex) Unlock() { 56 if mu.mutex != nil { 57 mu.mutex.Unlock() 58 } 59 }