github.com/gogf/gf/v2@v2.7.4/os/gmutex/gmutex_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 gmutex
     8  
     9  import "sync"
    10  
    11  // RWMutex is a high level RWMutex, which implements more rich features for mutex.
    12  type RWMutex struct {
    13  	sync.RWMutex
    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 *RWMutex) LockFunc(f func()) {
    21  	m.Lock()
    22  	defer m.Unlock()
    23  	f()
    24  }
    25  
    26  // RLockFunc locks the mutex for reading with given callback function `f`.
    27  // If there's a writing lock the mutex, it will block until the lock is released.
    28  //
    29  // It releases the lock after `f` is executed.
    30  func (m *RWMutex) RLockFunc(f func()) {
    31  	m.RLock()
    32  	defer m.RUnlock()
    33  	f()
    34  }
    35  
    36  // TryLockFunc tries locking the mutex for writing with given callback function `f`.
    37  // it returns true immediately if success, or if there's a write/reading lock on the mutex,
    38  // it returns false immediately.
    39  //
    40  // It releases the lock after `f` is executed.
    41  func (m *RWMutex) TryLockFunc(f func()) (result bool) {
    42  	if m.TryLock() {
    43  		result = true
    44  		defer m.Unlock()
    45  		f()
    46  	}
    47  	return
    48  }
    49  
    50  // TryRLockFunc tries locking the mutex for reading with given callback function `f`.
    51  // It returns true immediately if success, or if there's a writing lock on the mutex,
    52  // it returns false immediately.
    53  //
    54  // It releases the lock after `f` is executed.
    55  func (m *RWMutex) TryRLockFunc(f func()) (result bool) {
    56  	if m.TryRLock() {
    57  		result = true
    58  		defer m.RUnlock()
    59  		f()
    60  	}
    61  	return
    62  }