github.com/zhongdalu/gf@v1.0.0/g/internal/mutex/mutex.go (about) 1 // Copyright 2019 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 mutex provides switch of concurrent safe feature for sync.Mutex. 8 package mutex 9 10 import "sync" 11 12 // Mutex is a sync.Mutex with a switch of concurrent safe feature. 13 type Mutex struct { 14 sync.Mutex 15 safe bool 16 } 17 18 func New(unsafe ...bool) *Mutex { 19 mu := new(Mutex) 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 *Mutex) IsSafe() bool { 29 return mu.safe 30 } 31 32 func (mu *Mutex) Lock(force ...bool) { 33 if mu.safe || (len(force) > 0 && force[0]) { 34 mu.Mutex.Lock() 35 } 36 } 37 38 func (mu *Mutex) Unlock(force ...bool) { 39 if mu.safe || (len(force) > 0 && force[0]) { 40 mu.Mutex.Unlock() 41 } 42 }