From 2a200f5023b46dc09df9938d8b4608deac49c125 Mon Sep 17 00:00:00 2001 From: qydysky Date: Tue, 9 Jan 2024 23:57:50 +0800 Subject: [PATCH] 1 --- web/Web.go | 16 +++++++--------- web/Web_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/web/Web.go b/web/Web.go index 3efc923..3c2a09f 100644 --- a/web/Web.go +++ b/web/Web.go @@ -470,29 +470,31 @@ func (t *Exprier) Check(key string) error { return nil } -func (t *Exprier) LoopCheck(key string, dru time.Duration, whenfail func(key string, e error)) (breakLoop func()) { +func (t *Exprier) LoopCheck(key string, dru time.Duration, whenfail func(key string, e error)) (breakLoop func(), e error) { breakLoop = func() {} if t.Max <= 0 { return } if key == "" { + e = ErrNoFound whenfail(key, ErrNoFound) return } if t.m.Len() >= t.Max { + e = ErrOverflow whenfail(key, ErrOverflow) return } - c := make(chan struct{}) + var close atomic.Bool t.m.Store(key, time.Now().Add(dru)) breakLoop = func() { t.m.Delete(key) - close(c) + close.Store(true) } go func() { - for t.Max > 0 { + for !close.Load() && t.Max > 0 { ey, ok := t.m.LoadV(key).(time.Time) if !ok { whenfail(key, ErrNoFound) @@ -502,11 +504,7 @@ func (t *Exprier) LoopCheck(key string, dru time.Duration, whenfail func(key str whenfail(key, ErrExprie) return } - select { - case <-c: - return - case <-time.After(time.Until(ey) + time.Second): - } + time.Sleep(time.Until(ey) + time.Second) } }() return diff --git a/web/Web_test.go b/web/Web_test.go index 4a21010..dd5acc1 100644 --- a/web/Web_test.go +++ b/web/Web_test.go @@ -7,6 +7,7 @@ import ( "io" "net" "net/http" + "strconv" "strings" "testing" "time" @@ -307,3 +308,27 @@ func (t ResStruct) Write(w http.ResponseWriter) { } w.Write(data) } + +func Test1(b *testing.T) { + exp := Exprier{Max: 10} + + el := make(chan error, 100) + for i := 0; i < 20; i++ { + done, e := exp.LoopCheck(strconv.Itoa(i), time.Second*10, func(key string, e error) { + if e != nil { + el <- e + b.Log(key, e) + } + }) + if e != nil { + b.Fatal(e) + } + done() + } + + time.Sleep(time.Second * 3) + + if len(el) > 0 { + b.Fatal(<-el) + } +} -- 2.39.2