mirror of
https://github.com/fumiama/slowdo.git
synced 2026-06-04 23:40:30 +08:00
fix: dead lock
This commit is contained in:
20
job.go
20
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user