Files
gf/internal/rwmutex/rwmutex.go

78 lines
2.0 KiB
Go
Raw Permalink Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package rwmutex provides switch of concurrent safety feature for sync.RWMutex.
package rwmutex
2022-09-26 22:11:13 +08:00
import (
"sync"
)
2020-05-17 18:16:26 +08:00
// RWMutex is a sync.RWMutex with a switch for concurrent safe feature.
// If its attribute *sync.RWMutex is not nil, it means it's in concurrent safety usage.
// Its attribute *sync.RWMutex is nil in default, which makes this struct mush lightweight.
type RWMutex struct {
2022-09-26 22:11:13 +08:00
// Underlying mutex.
mutex *sync.RWMutex
}
// New creates and returns a new *RWMutex.
2021-02-08 17:57:21 +08:00
// The parameter `safe` is used to specify whether using this mutex in concurrent safety,
// which is false in default.
func New(safe ...bool) *RWMutex {
2020-04-07 11:29:42 +08:00
mu := Create(safe...)
return &mu
}
// Create creates and returns a new RWMutex object.
2021-02-08 17:57:21 +08:00
// The parameter `safe` is used to specify whether using this mutex in concurrent safety,
2020-04-07 11:29:42 +08:00
// which is false in default.
func Create(safe ...bool) RWMutex {
if len(safe) > 0 && safe[0] {
2022-09-26 22:11:13 +08:00
return RWMutex{
mutex: new(sync.RWMutex),
}
2019-06-19 09:06:52 +08:00
}
2022-09-26 22:11:13 +08:00
return RWMutex{}
}
2020-02-26 23:26:24 +08:00
// IsSafe checks and returns whether current mutex is in concurrent-safe usage.
func (mu *RWMutex) IsSafe() bool {
2022-09-26 22:11:13 +08:00
return mu.mutex != nil
}
2020-02-26 23:26:24 +08:00
// Lock locks mutex for writing.
// It does nothing if it is not in concurrent-safe usage.
2019-05-09 22:53:42 +08:00
func (mu *RWMutex) Lock() {
2022-09-26 22:11:13 +08:00
if mu.mutex != nil {
mu.mutex.Lock()
2019-06-19 09:06:52 +08:00
}
}
2020-02-26 23:26:24 +08:00
// Unlock unlocks mutex for writing.
// It does nothing if it is not in concurrent-safe usage.
2019-05-09 22:53:42 +08:00
func (mu *RWMutex) Unlock() {
2022-09-26 22:11:13 +08:00
if mu.mutex != nil {
mu.mutex.Unlock()
2019-06-19 09:06:52 +08:00
}
}
2020-02-26 23:26:24 +08:00
// RLock locks mutex for reading.
// It does nothing if it is not in concurrent-safe usage.
2019-05-09 22:53:42 +08:00
func (mu *RWMutex) RLock() {
2022-09-26 22:11:13 +08:00
if mu.mutex != nil {
mu.mutex.RLock()
2019-06-19 09:06:52 +08:00
}
}
2020-02-26 23:26:24 +08:00
// RUnlock unlocks mutex for reading.
// It does nothing if it is not in concurrent-safe usage.
2019-05-09 22:53:42 +08:00
func (mu *RWMutex) RUnlock() {
2022-09-26 22:11:13 +08:00
if mu.mutex != nil {
mu.mutex.RUnlock()
2019-06-19 09:06:52 +08:00
}
}