1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00
This commit is contained in:
2022-06-10 17:04:34 +08:00
parent 853b19fb02
commit 9bb232be93
22 changed files with 641 additions and 147 deletions

View File

@ -2,8 +2,6 @@ package locker
import "sync"
var _ RWLocker = &sync.RWMutex{}
func NewRWLocker() *sync.RWMutex {
return &sync.RWMutex{}
}

View File

@ -1,21 +1,54 @@
package locker
import "sync"
import (
"fmt"
)
var locks = make(map[string]sync.Locker)
// 资源锁
type SourceLocker struct {
m RWLocker
locks map[string]Locker
}
func NewSourceLocker() *SourceLocker {
return &SourceLocker{
m: NewRWLocker(),
locks: make(map[string]Locker),
}
}
func (s *SourceLocker) Lock(key string) {
s.m.RLock()
l, ok := s.locks[key]
if ok {
s.m.RUnlock()
func Lock(name string) {
if l, ok := locks[name]; ok {
l.Lock()
}
fmt.Println("加锁")
} else {
s.m.RUnlock()
new := &sync.Mutex{}
locks[name] = new
new.Lock()
s.m.Lock()
new := NewLocker()
s.locks[key] = new
s.m.Unlock()
new.Lock()
fmt.Println("初始加锁")
}
}
func Unlock(name string) {
if l, ok := locks[name]; ok {
func (s *SourceLocker) Unlock(key string) {
s.m.Lock()
if l, ok := s.locks[key]; ok {
l.Unlock()
// delete(s.locks, key)
fmt.Println("解锁")
}
s.m.Unlock()
}
func (s *SourceLocker) TryLock(key string) bool {
return false
}

View File

@ -0,0 +1,41 @@
package locker
import (
"sync"
"testing"
)
var sourcekey = "u-0001"
func TestSourceLocker(t *testing.T) {
l := NewSourceLocker()
c := 5
n := 0
wg := new(sync.WaitGroup)
wg.Add(c)
for i := 0; i < c; i++ {
go func() {
defer wg.Done()
l.Lock(sourcekey)
n++
l.Unlock(sourcekey)
}()
}
wg.Wait()
t.Log("n:", n)
}
func BenchmarkSourceLocker(b *testing.B) {
l := NewSourceLocker()
b.RunParallel(func(p *testing.PB) {
for p.Next() {
l.Lock(sourcekey)
l.Unlock(sourcekey)
}
})
}

View File

@ -0,0 +1,31 @@
package locker
import (
"sync"
"testing"
)
func TestSpinLock(t *testing.T) {
l := NewSpinLocker()
n := 10
c := 0
wg := new(sync.WaitGroup)
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
l.Lock()
c++
l.Unlock()
}()
}
wg.Wait()
l.Lock()
t.Log(c)
l.Unlock()
}