2019-02-02 16:18:25 +08:00
|
|
|
// Copyright 2019 gf Author(https://github.com/gogf/gf). 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
|
|
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
|
2019-06-18 17:31:48 +08:00
|
|
|
// Mutex is a sync.Mutex with a switch of concurrent safe feature.
|
2019-01-12 23:36:22 +08:00
|
|
|
type Mutex struct {
|
2019-06-19 09:06:52 +08:00
|
|
|
sync.Mutex
|
|
|
|
|
safe bool
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
|
2019-06-19 09:06:52 +08:00
|
|
|
func New(unsafe ...bool) *Mutex {
|
|
|
|
|
mu := new(Mutex)
|
|
|
|
|
if len(unsafe) > 0 {
|
|
|
|
|
mu.safe = !unsafe[0]
|
|
|
|
|
} else {
|
|
|
|
|
mu.safe = true
|
|
|
|
|
}
|
|
|
|
|
return mu
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (mu *Mutex) IsSafe() bool {
|
2019-06-19 09:06:52 +08:00
|
|
|
return mu.safe
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
|
2019-06-19 09:06:52 +08:00
|
|
|
func (mu *Mutex) Lock(force ...bool) {
|
|
|
|
|
if mu.safe || (len(force) > 0 && force[0]) {
|
|
|
|
|
mu.Mutex.Lock()
|
|
|
|
|
}
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
|
2019-06-19 09:06:52 +08:00
|
|
|
func (mu *Mutex) Unlock(force ...bool) {
|
|
|
|
|
if mu.safe || (len(force) > 0 && force[0]) {
|
|
|
|
|
mu.Mutex.Unlock()
|
|
|
|
|
}
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|