mirror of
https://github.com/fumiama/slowdo.git
synced 2026-06-05 07:50:27 +08:00
fix: dead lock
This commit is contained in:
20
job.go
20
job.go
@@ -5,7 +5,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Job[item, ctx any] struct {
|
type Job[ctx, item any] struct {
|
||||||
maxmait time.Duration
|
maxmait time.Duration
|
||||||
context ctx
|
context ctx
|
||||||
commit func(ctx, []item)
|
commit func(ctx, []item)
|
||||||
@@ -14,29 +14,29 @@ type Job[item, ctx any] struct {
|
|||||||
timer *time.Timer
|
timer *time.Timer
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewJob[item, ctx any](
|
func NewJob[ctx, item any](
|
||||||
maxwait time.Duration, context ctx, commit func(ctx, []item),
|
maxwait time.Duration, context ctx, commit func(ctx, []item),
|
||||||
) (*Job[item, ctx], error) {
|
) (*Job[ctx, item], error) {
|
||||||
if maxwait <= time.Millisecond {
|
if maxwait <= time.Millisecond {
|
||||||
return nil, ErrWaitTimeTooShort
|
return nil, ErrWaitTimeTooShort
|
||||||
}
|
}
|
||||||
return &Job[item, ctx]{
|
return &Job[ctx, item]{
|
||||||
maxmait: maxwait,
|
maxmait: maxwait,
|
||||||
context: context,
|
context: context,
|
||||||
commit: commit,
|
commit: commit,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (jb *Job[item, ctx]) Add(it item) {
|
func (jb *Job[ctx, item]) Add(it item) {
|
||||||
jb.itemmu.Lock()
|
jb.itemmu.Lock()
|
||||||
defer jb.itemmu.Unlock()
|
defer jb.itemmu.Unlock()
|
||||||
if len(jb.items) == 0 {
|
if len(jb.items) == 0 {
|
||||||
defer jb.collect()
|
jb.timer = time.AfterFunc(jb.maxmait, jb.Commit)
|
||||||
}
|
}
|
||||||
jb.items = append(jb.items, it)
|
jb.items = append(jb.items, it)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (jb *Job[item, ctx]) Commit() {
|
func (jb *Job[ctx, item]) Commit() {
|
||||||
jb.itemmu.Lock()
|
jb.itemmu.Lock()
|
||||||
if jb.timer != nil {
|
if jb.timer != nil {
|
||||||
jb.timer.Stop()
|
jb.timer.Stop()
|
||||||
@@ -52,9 +52,3 @@ func (jb *Job[item, ctx]) Commit() {
|
|||||||
jb.itemmu.Unlock()
|
jb.itemmu.Unlock()
|
||||||
jb.commit(jb.context, itemscp)
|
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)
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user