Skip to content

Commit 26b3fe8

Browse files
committed
allow running multiple funcs on a hold token
1 parent e4c9101 commit 26b3fe8

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

keeper.go

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -237,13 +237,19 @@ type holdTokenImpl struct {
237237
listeningCtx context.Context
238238
deadlineCtx context.Context
239239
releasingFunc func()
240+
241+
shuttingFuncCount int32
242+
runningFuncCount int32
240243
}
241244

242245
func newHoldTokenImpl(listeningCtx context.Context, deadlineCtx context.Context, releasingFunc func()) *holdTokenImpl {
243246
return &holdTokenImpl{
244247
listeningCtx: listeningCtx,
245248
deadlineCtx: deadlineCtx,
246249
releasingFunc: releasingFunc,
250+
251+
shuttingFuncCount: 0,
252+
runningFuncCount: 0,
247253
}
248254
}
249255

@@ -264,23 +270,38 @@ func (kt *holdTokenImpl) DeadlineContext() context.Context {
264270
}
265271

266272
func (kt *holdTokenImpl) DoOnShutdown(f func(deadlineCtx context.Context)) {
273+
atomic.AddInt32(&kt.shuttingFuncCount, 1)
267274
go func() {
268-
defer kt.Release()
275+
defer func() {
276+
if atomic.AddInt32(&kt.shuttingFuncCount, -1) == 0 {
277+
kt.Release()
278+
}
279+
}()
269280
kt.ListenShutdown()
270281
f(kt.deadlineCtx)
271282
}()
272283
}
273284

274285
func (kt *holdTokenImpl) GoRun(f func()) {
286+
atomic.AddInt32(&kt.runningFuncCount, 1)
275287
go func() {
276-
defer kt.Release()
288+
defer func() {
289+
if atomic.AddInt32(&kt.runningFuncCount, -1) == 0 {
290+
kt.Release()
291+
}
292+
}()
277293
f()
278294
}()
279295
}
280296

281297
func (kt *holdTokenImpl) GoRunWithCtx(f func(ctx context.Context)) {
298+
atomic.AddInt32(&kt.runningFuncCount, 1)
282299
go func() {
283-
defer kt.Release()
300+
defer func() {
301+
if atomic.AddInt32(&kt.runningFuncCount, -1) == 0 {
302+
kt.Release()
303+
}
304+
}()
284305
f(kt.listeningCtx)
285306
}()
286307
}

0 commit comments

Comments
 (0)