gopkg/easylock/lock_segment.go

69 lines
1.6 KiB
Go
Raw Permalink Normal View History

2021-12-24 23:55:35 +08:00
// Package easylock ...
2021-02-24 23:44:14 +08:00
//
// Description : 分段的锁
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-02-24 23:44:14 +08:00
//
// Date : 2021-02-24 10:44 下午
package easylock
2021-07-25 18:50:56 +08:00
import "git.zhangdeman.cn/zhangdeman/gopkg/util"
2021-02-24 23:44:14 +08:00
// NewSegment 获取分段锁
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-02-24 23:44:14 +08:00
//
// 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,
2021-04-01 16:58:34 +08:00
lockCnt: &LockCnt{
Write: 0,
Read: 0,
},
2021-02-24 23:44:14 +08:00
}
for i := 0; i < segmentCnt; i++ {
s.lockTable[i] = NewLock()
}
return s, nil
}
type segment struct {
lockTable []EasyLock
segmentCnt int
2021-04-01 16:58:34 +08:00
lockCnt *LockCnt
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 {
2021-04-01 16:58:34 +08:00
defer s.AddRLockCnt(s.lockCnt)
2021-04-01 16:28:23 +08:00
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 {
2021-04-01 16:58:34 +08:00
defer s.DecreaseLockCnt(s.lockCnt)
2021-04-01 16:28:23 +08:00
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 {
2021-04-01 16:58:34 +08:00
defer s.AddRLockCnt(s.lockCnt)
2021-04-01 16:28:23 +08:00
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 {
2021-04-01 16:58:34 +08:00
defer s.DecreaseRLockCnt(s.lockCnt)
2021-04-01 16:28:23 +08:00
o := s.ParseOption(optionFuncList...)
return s.lockTable[util.GetHashIDMod(o.flag, s.segmentCnt)].RUnlock()
2021-02-24 23:44:14 +08:00
}
2021-04-01 16:58:34 +08:00
func (s *segment) GetLockCnt() *LockCnt {
return s.lockCnt
}