working commit

This commit is contained in:
2026-02-24 15:52:31 +02:00
parent e2e4ec1776
commit d6d2721c88
6 changed files with 178 additions and 16 deletions
+66
View File
@@ -0,0 +1,66 @@
package locker
import (
"sync"
)
type Elem struct {
Pipe chan bool
Usage int
}
func NewElem() *Elem {
return &Elem{
Pipe: make(chan bool, 1),
}
}
type Locker struct {
mtx sync.Mutex
lMap map[string]*Elem
}
func NewLocker() *Locker {
lock := &Locker{
lMap: make(map[string]*Elem),
}
return lock
}
func (lock *Locker) WaitAndLock(name string) {
lock.mtx.Lock()
p, exist := lock.lMap[name]
if !exist {
p = NewElem()
lock.lMap[name] = p
p.Pipe <- true
}
p.Usage += 1
lock.mtx.Unlock()
select {
case <-p.Pipe:
// NOP
}
}
func (lock *Locker) Done(name string) {
lock.mtx.Lock()
p, exist := lock.lMap[name]
if exist {
p.Pipe <- true
if p.Usage > 0 {
p.Usage -= 1
}
}
garbageKeys := make([]string, 0)
for key, _ := range lock.lMap {
elem := lock.lMap[key]
if elem.Usage == 0 && key != name {
garbageKeys = append(garbageKeys, key)
}
}
for _, key := range garbageKeys {
delete(lock.lMap, key)
}
lock.mtx.Unlock()
}
+62
View File
@@ -0,0 +1,62 @@
package locker
import (
"fmt"
"math/rand"
"sync"
"testing"
"time"
)
type Runner struct {
lock *Locker
res sync.Map
}
func NewRunner() *Runner {
return &Runner{
lock: NewLocker(),
}
}
func (r *Runner) Run(wg *sync.WaitGroup, resName string, t *testing.T) {
for n := 2; n < 1000; n++ {
r.lock.WaitAndLock(resName)
val := fmt.Sprintf("%d", n)
r.res.Store(resName, val)
td := time.Duration(rand.Uint64()%1000 + 1)
time.Sleep(td * time.Nanosecond)
foo, exist := r.res.Load(resName)
if !exist {
t.Errorf("not exist!\n")
}
if foo != val {
t.Errorf("not val!\n")
}
r.res.Delete(resName)
r.lock.Done(resName)
time.Sleep(1 * time.Millisecond)
}
wg.Done()
}
func TestLocker(t *testing.T) {
run := NewRunner()
var wg sync.WaitGroup
for n := 1; n < 200; n++ {
go run.Run(&wg, "foo", t)
wg.Add(1)
}
for n := 1; n < 200; n++ {
go run.Run(&wg, "foo/bare", t)
wg.Add(1)
}
for n := 1; n < 200; n++ {
go run.Run(&wg, "foo/bare/foo", t)
wg.Add(1)
}
wg.Wait()
}