2021-02-24 23:44:14 +08:00
|
|
|
// Package easylock...
|
|
|
|
//
|
|
|
|
// Description : 分段的锁
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<张德满>
|
|
|
|
//
|
|
|
|
// Date : 2021-02-24 10:44 下午
|
|
|
|
package easylock
|
|
|
|
|
|
|
|
import "github.com/go-developer/gopkg/util"
|
|
|
|
|
|
|
|
// NewSegment 获取分段锁
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<张德满>
|
|
|
|
//
|
|
|
|
// Date : 11:20 下午 2021/2/24
|
|
|
|
func NewSegment(segmentCnt int) (EasyLock, error) {
|
|
|
|
if segmentCnt <= 0 {
|
|
|
|
return nil, segmentError()
|
|
|
|
}
|
|
|
|
s := &segment{
|
|
|
|
lockTable: make([]EasyLock, segmentCnt),
|
|
|
|
segmentCnt: segmentCnt,
|
|
|
|
}
|
|
|
|
for i := 0; i < segmentCnt; i++ {
|
|
|
|
s.lockTable[i] = NewLock()
|
|
|
|
}
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type segment struct {
|
|
|
|
lockTable []EasyLock
|
|
|
|
segmentCnt int
|
2021-04-01 16:28:23 +08:00
|
|
|
base
|
2021-02-24 23:44:14 +08:00
|
|
|
}
|
|
|
|
|
2021-04-01 16:28:23 +08:00
|
|
|
func (s *segment) Lock(optionFuncList ...OptionFunc) error {
|
|
|
|
o := s.ParseOption(optionFuncList...)
|
|
|
|
return s.lockTable[util.GetHashIDMod(o.flag, s.segmentCnt)].Lock()
|
2021-02-24 23:44:14 +08:00
|
|
|
}
|
|
|
|
|
2021-04-01 16:28:23 +08:00
|
|
|
func (s *segment) Unlock(optionFuncList ...OptionFunc) error {
|
|
|
|
o := s.ParseOption(optionFuncList...)
|
|
|
|
return s.lockTable[util.GetHashIDMod(o.flag, s.segmentCnt)].Unlock()
|
2021-02-24 23:44:14 +08:00
|
|
|
}
|
|
|
|
|
2021-04-01 16:28:23 +08:00
|
|
|
func (s *segment) RLock(optionFuncList ...OptionFunc) error {
|
|
|
|
o := s.ParseOption(optionFuncList...)
|
|
|
|
return s.lockTable[util.GetHashIDMod(o.flag, s.segmentCnt)].RLock()
|
2021-02-24 23:44:14 +08:00
|
|
|
}
|
|
|
|
|
2021-04-01 16:28:23 +08:00
|
|
|
func (s *segment) RUnlock(optionFuncList ...OptionFunc) error {
|
|
|
|
o := s.ParseOption(optionFuncList...)
|
|
|
|
return s.lockTable[util.GetHashIDMod(o.flag, s.segmentCnt)].RUnlock()
|
2021-02-24 23:44:14 +08:00
|
|
|
}
|