diff options
author | Wim <wim@42.be> | 2023-08-05 20:43:19 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-08-05 20:43:19 +0200 |
commit | 56e7bd01ca09ad52b0c4f48f146a20a4f1b78696 (patch) | |
tree | b1355645342667209263cbd355dc0b4254f1e8fe /vendor/github.com/lrstanley/girc/internal | |
parent | 9459495484d6e06a3d46de64fccd8d06f7ccc72c (diff) | |
download | matterbridge-msglm-56e7bd01ca09ad52b0c4f48f146a20a4f1b78696.tar.gz matterbridge-msglm-56e7bd01ca09ad52b0c4f48f146a20a4f1b78696.tar.bz2 matterbridge-msglm-56e7bd01ca09ad52b0c4f48f146a20a4f1b78696.zip |
Diffstat (limited to 'vendor/github.com/lrstanley/girc/internal')
-rw-r--r-- | vendor/github.com/lrstanley/girc/internal/ctxgroup/ctxgroup.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/vendor/github.com/lrstanley/girc/internal/ctxgroup/ctxgroup.go b/vendor/github.com/lrstanley/girc/internal/ctxgroup/ctxgroup.go new file mode 100644 index 00000000..e66ed2b5 --- /dev/null +++ b/vendor/github.com/lrstanley/girc/internal/ctxgroup/ctxgroup.go @@ -0,0 +1,67 @@ +// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use +// of this source code is governed by the MIT license that can be found in +// the LICENSE file. + +package ctxgroup + +import ( + "context" + "sync" +) + +// A Group is a collection of goroutines working on subtasks that are part of +// the same overall task. +type Group struct { + ctx context.Context + cancel func() + + wg sync.WaitGroup + + errOnce sync.Once + err error +} + +// New returns a new Group and an associated context derived from ctx. +// Obtain the derived context from calling Group.Context(). +// +// The derived context is canceled the first time a function passed to Go +// returns a non-nil error or the first time Wait returns, whichever occurs +// first. +func New(ctx context.Context) *Group { + nctx, cancel := context.WithCancel(ctx) + return &Group{ctx: nctx, cancel: cancel} +} + +// Context returns the context for this group. It may be canceled by the first +// function to return a non-nil error. +func (g *Group) Context() context.Context { + return g.ctx +} + +// Wait blocks until all function calls from the Go method have returned, then +// returns the first non-nil error (if any) from them. +func (g *Group) Wait() error { + g.wg.Wait() + if g.cancel != nil { + g.cancel() + } + return g.err +} + +// Go calls the given function in a new goroutine. The first call to return a +// non-nil error cancels the group; its error will be returned by Wait. +func (g *Group) Go(f func(ctx context.Context) error) { + g.wg.Add(1) + go func() { + defer g.wg.Done() + + if err := f(g.ctx); err != nil { + g.errOnce.Do(func() { + g.err = err + if g.cancel != nil { + g.cancel() + } + }) + } + }() +} |