2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2019-01-23 13:01:58 +08:00
|
|
|
//
|
|
|
|
// 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,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2019-01-23 13:01:58 +08:00
|
|
|
|
2019-06-18 17:31:48 +08:00
|
|
|
// Package mutex provides switch of concurrent safe feature for sync.Mutex.
|
2019-01-12 23:36:22 +08:00
|
|
|
package mutex
|
|
|
|
|
2022-09-26 22:11:13 +08:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
2019-01-12 23:36:22 +08:00
|
|
|
|
2020-05-17 18:16:26 +08:00
|
|
|
// Mutex is a sync.Mutex with a switch for concurrent safe feature.
|
2019-01-12 23:36:22 +08:00
|
|
|
type Mutex struct {
|
2022-09-26 22:11:13 +08:00
|
|
|
// Underlying mutex.
|
|
|
|
mutex *sync.Mutex
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
2019-07-23 23:20:27 +08:00
|
|
|
// 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,
|
2019-07-23 23:20:27 +08:00
|
|
|
// 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{}
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
2022-09-26 22:11:13 +08:00
|
|
|
// IsSafe checks and returns whether current mutex is in concurrent-safe usage.
|
2019-01-12 23:36:22 +08:00
|
|
|
func (mu *Mutex) IsSafe() bool {
|
2022-09-26 22:11:13 +08:00
|
|
|
return mu.mutex != nil
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
2022-09-26 22:11:13 +08:00
|
|
|
// Lock locks mutex for writing.
|
|
|
|
// It does nothing if it is not in concurrent-safe usage.
|
2019-07-23 23:20:27 +08:00
|
|
|
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
|
|
|
}
|
2019-01-12 23:36:22 +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.
|
2019-07-23 23:20:27 +08:00
|
|
|
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
|
|
|
}
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|