From 27c4fe5259a4ba47f94f2095894eaf131ee43708 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BA=90=E6=96=87=E9=9B=A8?= <41315874+fumiama@users.noreply.github.com> Date: Tue, 1 Oct 2024 16:40:58 +0900 Subject: [PATCH] fix: dead lock --- job.go | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/job.go b/job.go index 3fa7cbd..f70a52a 100644 --- a/job.go +++ b/job.go @@ -5,7 +5,7 @@ import ( "time" ) -type Job[item, ctx any] struct { +type Job[ctx, item any] struct { maxmait time.Duration context ctx commit func(ctx, []item) @@ -14,29 +14,29 @@ type Job[item, ctx any] struct { timer *time.Timer } -func NewJob[item, ctx any]( +func NewJob[ctx, item any]( maxwait time.Duration, context ctx, commit func(ctx, []item), -) (*Job[item, ctx], error) { +) (*Job[ctx, item], error) { if maxwait <= time.Millisecond { return nil, ErrWaitTimeTooShort } - return &Job[item, ctx]{ + return &Job[ctx, item]{ maxmait: maxwait, context: context, commit: commit, }, nil } -func (jb *Job[item, ctx]) Add(it item) { +func (jb *Job[ctx, item]) Add(it item) { jb.itemmu.Lock() defer jb.itemmu.Unlock() if len(jb.items) == 0 { - defer jb.collect() + jb.timer = time.AfterFunc(jb.maxmait, jb.Commit) } jb.items = append(jb.items, it) } -func (jb *Job[item, ctx]) Commit() { +func (jb *Job[ctx, item]) Commit() { jb.itemmu.Lock() if jb.timer != nil { jb.timer.Stop() @@ -52,9 +52,3 @@ func (jb *Job[item, ctx]) Commit() { jb.itemmu.Unlock() jb.commit(jb.context, itemscp) } - -func (jb *Job[item, ctx]) collect() { - jb.itemmu.Lock() - defer jb.itemmu.Unlock() - jb.timer = time.AfterFunc(jb.maxmait, jb.Commit) -}