mirror of
https://github.com/lightningnetwork/lnd.git
synced 2026-08-13 12:32:48 +02:00
lnutils: add ContextFromQuit to bridge quit channels to contexts
In this commit, we add ContextFromQuit, a utility for bridging the quit
channel shutdown pattern to context.Context-based cancellation.
Several subsystems in lnd use a plain quit <-chan struct{} for
cooperative shutdown rather than a context.Context. When those
subsystems need to await a Future[error], which uses a context for
cancellation, they need a way to derive a context that is cancelled
when the quit channel closes.
ContextFromQuit does exactly that: it returns a context tied to
context.Background() plus a cancel function, and spins up a minimal
goroutine that cancels the context as soon as quit is closed. The
returned cancel must be called (deferred at the call site) so the
goroutine exits when the enclosing operation completes normally before
shutdown.
This is a pure utility with no policy and no default timeout, so
callers remain in full control of lifetime.
This commit is contained in:
parent
4e0992fa4e
commit
eadea00aeb
1 changed files with 22 additions and 0 deletions
22
lnutils/context.go
Normal file
22
lnutils/context.go
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
package lnutils
|
||||
|
||||
import "context"
|
||||
|
||||
// ContextFromQuit returns a context that is cancelled when the provided quit
|
||||
// channel is closed. The returned cancel function MUST be called to avoid
|
||||
// goroutine leaks.
|
||||
func ContextFromQuit(quit <-chan struct{}) (context.Context,
|
||||
context.CancelFunc) {
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-quit:
|
||||
cancel()
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}()
|
||||
|
||||
return ctx, cancel
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue