gf/internal/mutex/mutex.go

60 lines
1.5 KiB
Go
Raw 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.
2019-06-18 17:31:48 +08:00
// Package mutex provides switch of concurrent safe feature for sync.Mutex.
package mutex
2022-09-26 22:11:13 +08:00
import (
"sync"
)
2020-05-17 18:16:26 +08:00
// Mutex is a sync.Mutex with a switch for concurrent safe feature.
type Mutex struct {
2022-09-26 22:11:13 +08:00
// Underlying mutex.
mutex *sync.Mutex
}
// New creates and returns a new *Mutex.
2022-09-26 22:11:13 +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) *Mutex {
2022-09-26 22:11:13 +08:00
mu := Create(safe...)
return &mu
}
// Create creates and returns a new Mutex object.
// The parameter `safe` is used to specify whether using this mutex in concurrent safety,
// which is false in default.
func Create(safe ...bool) Mutex {
if len(safe) > 0 && safe[0] {
return Mutex{
mutex: new(sync.Mutex),
}
2019-06-19 09:06:52 +08:00
}
2022-09-26 22:11:13 +08:00
return Mutex{}
}
2022-09-26 22:11:13 +08:00
// IsSafe checks and returns whether current mutex is in concurrent-safe usage.
func (mu *Mutex) IsSafe() bool {
2022-09-26 22:11:13 +08:00
return mu.mutex != nil
}
2022-09-26 22:11:13 +08:00
// Lock locks mutex for writing.
// It does nothing if it is not in concurrent-safe usage.
func (mu *Mutex) Lock() {
2022-09-26 22:11:13 +08:00
if mu.mutex != nil {
mu.mutex.Lock()
2019-06-19 09:06:52 +08:00
}
}
2022-09-26 22:11:13 +08:00
// Unlock unlocks mutex for writing.
// It does nothing if it is not in concurrent-safe usage.
func (mu *Mutex) Unlock() {
2022-09-26 22:11:13 +08:00
if mu.mutex != nil {
mu.mutex.Unlock()
2019-06-19 09:06:52 +08:00
}
}