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-07-23 23:20:27 +08:00
|
|
|
// New creates and returns a new *Mutex.
|
|
|
|
// The parameter <safe> is used to specify whether using this mutex in concurrent-safety,
|
|
|
|
// which is false in default.
|
|
|
|
func New(safe ...bool) *Mutex {
|
2019-06-19 09:06:52 +08:00
|
|
|
mu := new(Mutex)
|
2019-07-23 23:20:27 +08:00
|
|
|
if len(safe) > 0 {
|
|
|
|
mu.safe = safe[0]
|
2019-06-19 09:06:52 +08:00
|
|
|
} else {
|
2019-07-23 23:20:27 +08:00
|
|
|
mu.safe = false
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
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-07-23 23:20:27 +08:00
|
|
|
func (mu *Mutex) Lock() {
|
|
|
|
if mu.safe {
|
2019-06-19 09:06:52 +08:00
|
|
|
mu.Mutex.Lock()
|
|
|
|
}
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|
|
|
|
|
2019-07-23 23:20:27 +08:00
|
|
|
func (mu *Mutex) Unlock() {
|
|
|
|
if mu.safe {
|
2019-06-19 09:06:52 +08:00
|
|
|
mu.Mutex.Unlock()
|
|
|
|
}
|
2019-01-12 23:36:22 +08:00
|
|
|
}
|