X-Git-Url: https://git.arvados.org/lightning.git/blobdiff_plain/00b2acd54dd1aa412f6f2bddc24b1bbb31c7ae3f..b9a352b3c94fbefd189bf72694ef52fe561f0515:/throttle.go diff --git a/throttle.go b/throttle.go index da338f62f5..8b087eeae2 100644 --- a/throttle.go +++ b/throttle.go @@ -1,3 +1,7 @@ +// Copyright (C) The Lightning Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + package lightning import ( @@ -15,7 +19,12 @@ type throttle struct { } func (t *throttle) Acquire() { - t.setupOnce.Do(func() { t.ch = make(chan bool, t.Max) }) + t.setupOnce.Do(func() { + if t.Max < 1 { + panic("throttle.Max < 1") + } + t.ch = make(chan bool, t.Max) + }) t.wg.Add(1) t.ch <- true } @@ -40,3 +49,16 @@ func (t *throttle) Wait() error { t.wg.Wait() return t.Err() } + +func (t *throttle) Go(f func() error) error { + t.Acquire() + if t.Err() != nil { + t.Release() + return t.Err() + } + go func() { + t.Report(f()) + t.Release() + }() + return nil +}