github.com/wangyougui/gf/v2@v2.6.5/os/gmutex/gmutex_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/wangyougui/gf. 6 7 package gmutex 8 9 import "sync" 10 11 // Mutex is a high level Mutex, which implements more rich features for mutex. 12 type Mutex struct { 13 sync.Mutex 14 } 15 16 // LockFunc locks the mutex for writing with given callback function `f`. 17 // If there's a write/reading lock the mutex, it will block until the lock is released. 18 // 19 // It releases the lock after `f` is executed. 20 func (m *Mutex) LockFunc(f func()) { 21 m.Lock() 22 defer m.Unlock() 23 f() 24 } 25 26 // TryLockFunc tries locking the mutex for writing with given callback function `f`. 27 // it returns true immediately if success, or if there's a write/reading lock on the mutex, 28 // it returns false immediately. 29 // 30 // It releases the lock after `f` is executed. 31 func (m *Mutex) TryLockFunc(f func()) (result bool) { 32 if m.TryLock() { 33 result = true 34 defer m.Unlock() 35 f() 36 } 37 return 38 }