taskgroup

package module
v0.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2024 License: BSD-3-Clause Imports: 1 Imported by: 70

README

taskgroup

GoDoc

A *taskgroup.Group represents a group of goroutines working on related tasks. New tasks can be added to the group at will, and the caller can wait until all tasks are complete. Errors are automatically collected and delivered to a user-provided callback in a single goroutine. This does not replace the full generality of Go's built-in features, but it simplifies some of the plumbing for common concurrent tasks.

Here is a working example in the Go Playground.

Rationale

Go provides powerful concurrency primitives, including goroutines, channels, select, and the standard library's sync package. In some common situations, however, managing goroutine lifetimes can become unwieldy using only what is built in.

For example, consider the case of copying a large directory tree: Walk through a source directory recursively, creating a parallel target directory structure and starting a goroutine to copy each of the files concurrently. In outline:

func copyTree(source, target string) error {
	err := filepath.Walk(source, func(path string, fi os.FileInfo, err error) error {
		adjusted := adjustPath(path)
		if fi.IsDir() {
			return os.MkdirAll(adjusted, 0755)
		}
		go copyFile(adjusted, target)
		return nil
	})
	if err != nil {
		// ... clean up the output directory ...
	}
	return err
}

This solution is deficient, however, as it does not provide any way to detect when all the file copies are finished. To do that we will typically use a sync.WaitGroup:

var wg sync.WaitGroup
...
wg.Add(1)
go func() {
    defer wg.Done()
    copyFile(adjusted, target)
}()
...
wg.Wait() // block until all the tasks signal done

In addition, we need to handle errors. Copies might fail (the disk may fill, or there might be a permissions error). For some applications it might suffice to log the error and continue, but usually in case of error we should back out and clean up the partial state.

To do that, we need to capture the return value from the function inside the goroutine―and that will require us either to add a lock or plumb in another channel:

errs := make(chan error)
...
go copyFile(adjusted, target, errs)

Since multiple operations can be running in parallel, we will also need another goroutine to drain the errors channel and accumulate the results somewhere:

var failures []error
go func() {
    for e := range errs {
        failures = append(failures, e)
    }
}()
...
wg.Wait()
close(errs)

Once the work is finished, we must also detect when the error collector is done, so we can examine the failures without a data race. We'll need another channel or wait group to signal for this:

var failures []error
edone := make(chan struct{})
go func() {
    defer close(edone)
    for e := range errs {
        failures = append(failures, e)
    }
}()
...
wg.Wait()   // all the workers are done
close(errs) // signal the error collector to stop
<-edone     // wait for the error collector to be done

Another issue is, if one of the file copies fails, we don't necessarily want to wait around for all the copies to finish before reporting the error―we want to stop everything and clean up the whole operation. Typically we would do this using a context.Context:

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	...
	copyFile(ctx, adjusted, target, errs)

Now copyFile will have to check for ctx to be finished:

func copyFile(ctx context.Context, source, target string, errs chan<- error) {
	if ctx.Err() != nil {
		return
	}
 	// ... do the copy as normal, or propagate an error
}

Finally, we want the ability to to limit the number of concurrent copies. Even if the host has plenty of memory and CPU, unbounded concurrency is likely to run us out of file descriptors. To handle this we might use a semaphore or a throttling channel:

throttle := make(chan struct{}, 64)  // allow up to 64 concurrent copies
go func() {
   throttle <- struct{}{} // block until the throttle has a free slot
   defer func() { wg.Done(); <-throttle }()
   copyFile(ctx, adjusted, target, errs)
}()

So far, we're up to four channels (errs, edone, context, and throttle) plus a wait group. The point to note is that while these tools are easy to express what we want, it can be tedious to wire them all together and keep track of the current state of the system.

The taskgroup package exists to handle the plumbing for the common case of a group of tasks that are all working on a related outcome (e.g., copying a directory structure), and where an error on the part of any single task may be grounds for terminating the work as a whole.

The package provides a taskgroup.Group type that has built-in support for some of these concerns:

  • Limiting the number of active goroutines.
  • Collecting and filtering errors.
  • Waiting for completion and delivering status.

A taskgroup.Group collects error values from each task and can deliver them to a user-provided callback. The callback can filter them or take other actions (such as cancellation). Invocations of the callback are all done from a single goroutine so it is safe to manipulate local resources without a lock.

A group does not directly support cancellation, but integrates cleanly with the standard context package. A context.CancelFunc can be used as a trigger to signal the whole group when an error occurs.

A task is expressed as a func() error, and is added to a group using the Go method:

g := taskgroup.New(nil).Go(myTask)

Any number of tasks may be added, and it is safe to do so from multiple goroutines concurrently. To wait for the tasks to finish, use:

err := g.Wait()

Wait blocks until all the tasks in the group have returned, and then reports the first non-nil error returned by any of the worker tasks.

An implementation of this example can be found in examples/copytree/copytree.go.

Filtering Errors

The taskgroup.New function takes an optional callback to be invoked for each non-nil error reported by a task in the group. The callback may choose to propagate, replace, or discard the error. For example, suppose we want to ignore "file not found" errors from a copy operation:

g := taskgroup.New(func(err error) error {
   if os.IsNotExist(err) {
      return nil // ignore files that do not exist
   }
   return err
})

Controlling Concurrency

The Limit method supports limiting the number of concurrently active goroutines in the group. It returns a start function that adds goroutines to the group, but will will block when the limit of goroutines is reached until some of the goroutines already running have finished.

For example:

// Allow at most 3 concurrently-active goroutines in the group.
g, start := taskgroup.New(nil).Limit(3)

// Start tasks by calling the function returned by taskgroup.Limit:
start(task1)
start(task2)
start(task3)
start(task4) // blocks until one of the previous tasks is finished
// ...

Solo Tasks

In some cases it is useful to have a solo background task to handle a separate concern, such as collecting the results from a batch of concurrent workers.

For example, suppose we have a group of tasks processing a complex search, and we want to aggregate the results. We don't want to add this task to the same group as the workers, because it needs to know when the rest of the workers have all completed. On the other hand, creating another whole group just for one task is overkill, since we only need one additional goroutine.

To handle such cases, the Go constructor is helpful: It manages a single background goroutine with a separate wait:

results := make(chan int)
s := taskgroup.Go(func() (total int) {
    for v := range results {
        total += v
    }
    return
})

g := taskgroup.New(nil)
for i := 0; i < numTasks; i++ {
    batch := newBatch(i)
    g.Go(func() error {
        return search(batch)
    })
}

// Wait for the workers to finish, then signal the collector to stop.
g.Wait(); close(results)

// Now get the final result.
fmt.Println(s.Wait())

Documentation

Overview

Package taskgroup manages collections of cooperating goroutines. It defines a Group that handles waiting for goroutine termination and the propagation of error values. The caller may provide a callback to filter and respond to task errors.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrorFunc

type ErrorFunc func(error) error

An ErrorFunc is called by a group each time a task reports an error. Its return value replaces the reported error, so the ErrorFunc can filter or suppress errors by modifying or discarding the input error.

func Listen

func Listen(f func(error)) ErrorFunc

Listen creates an ErrorFunc that reports each non-nil task error to f. The resulting ErrorFunc returns task errors unmodified.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/creachadair/taskgroup"
)

func main() {
	g := taskgroup.New(taskgroup.Listen(func(e error) {
		fmt.Println(e)
	}))
	g.Go(func() error { return errors.New("heard you") })
	fmt.Println(g.Wait()) // the error was preserved
}
Output:
heard you
heard you

func Trigger

func Trigger(f func()) ErrorFunc

Trigger creates an ErrorFunc that calls f each time a task reports an error. The resulting ErrorFunc returns task errors unmodified.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/creachadair/taskgroup"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	const badTask = 5

	// Construct a group in which any task error cancels the context.
	g := taskgroup.New(taskgroup.Trigger(cancel))

	for i := 0; i < 10; i++ {
		i := i
		g.Go(func() error {
			if i == badTask {
				return fmt.Errorf("task %d failed", i)
			}
			select {
			case <-ctx.Done():
				return ctx.Err()
			case <-time.After(10 * time.Second):
				return nil
			}
		})
	}

	if err := g.Wait(); err == nil {
		log.Fatal("I expected an error here")
	} else {
		fmt.Println(err.Error())
	}
}
Output:
task 5 failed

type Group

type Group struct {
	// contains filtered or unexported fields
}

A Group manages a collection of cooperating goroutines. New tasks are added to the group with the Go method. Call the Wait method to wait for the tasks to complete. A zero value is ready for use, but must not be copied after its first use.

The group collects any errors returned by the tasks in the group. The first non-nil error reported by any task (and not otherwise filtered) is returned from the Wait method.

Example
package main

import (
	"fmt"

	"github.com/creachadair/taskgroup"
)

func main() {
	msg := make(chan string)
	g := taskgroup.New(nil)
	g.Go(func() error {
		msg <- "ping"
		fmt.Println(<-msg)
		return nil
	})
	g.Go(func() error {
		fmt.Println(<-msg)
		msg <- "pong"
		return nil
	})
	g.Wait()
	fmt.Println("<done>")

}
Output:
ping
pong
<done>

func New

func New(ef ErrorFunc) *Group

New constructs a new empty group. If ef != nil, it is called for each error reported by a task running in the group. The value returned by ef replaces the task's error. If ef == nil, errors are not filtered.

Calls to ef are issued by a single goroutine, so it is safe for ef to manipulate local data structures without additional locking.

func (*Group) Go

func (g *Group) Go(task Task) *Group

Go runs task in a new goroutine in g, and returns g to permit chaining.

func (*Group) Limit

func (g *Group) Limit(n int) (*Group, func(Task) *Group)

Limit returns g and a function that starts each task passed to it in g, allowing no more than n tasks to be active concurrently. If n ≤ 0, the start function is equivalent to g.Go, which enforces no limit.

The limiting mechanism is optional, and the underlying group is not restricted. A call to the start function will block until a slot is available, but calling g.Go directly will add a task unconditionally and will not take up a limiter slot.

Example
var p peakValue

g, start := taskgroup.New(nil).Limit(4)
for i := 0; i < 100; i++ {
	start(func() error {
		p.inc()
		defer p.dec()
		time.Sleep(1 * time.Microsecond)
		return nil
	})
}
g.Wait()
fmt.Printf("Max active ≤ 4: %v\n", p.max <= 4)
Output:
Max active ≤ 4: true

func (*Group) Wait

func (g *Group) Wait() error

Wait blocks until all the goroutines currently active in the group have returned, and all reported errors have been delivered to the callback. It returns the first non-nil error returned by any of the goroutines in the group and not filtered by an ErrorFunc.

It is safe to call Wait concurrently from multiple goroutines, but as with sync.WaitGroup no tasks can be added to g while any call to Wait is in progress. Once all Wait calls have returned, the group is ready for reuse.

type Result added in v0.6.0

type Result[T any] struct {
	Value T
	Err   error
}

A Result is a pair of an arbitrary value and an error.

func (Result[T]) Get added in v0.6.1

func (r Result[T]) Get() (T, error)

Get returns the fields of r as results. It is a convenience method for unpacking the results of a Call.

Typical usage:

s := taskgroup.Call(func() (int, error) { ... })
v, err := s.Wait().Get()

type Single added in v0.4.0

type Single[T any] struct {
	// contains filtered or unexported fields
}

A single manages a single background goroutine. The task is started when the value is first created, and the caller can use the Wait method to block until it has exited.

Example
package main

import (
	"fmt"
	"math/rand"

	"github.com/creachadair/taskgroup"
)

func shuffled(n int) []int {
	vs := make([]int, n)
	for i := range vs {
		vs[i] = i + 1
	}
	rand.Shuffle(n, func(i, j int) {
		vs[i], vs[j] = vs[j], vs[i]
	})
	return vs
}

func main() {
	results := make(chan int)

	// Start a task to collect the results of a "search" process.
	s := taskgroup.Go(func() (total int) {
		for v := range results {
			total += v
		}
		return
	})

	const numTasks = 25
	input := shuffled(500)

	// Start a bunch of tasks to find elements in the input...
	g := taskgroup.New(nil)
	for i := 0; i < numTasks; i++ {
		target := i + 1
		g.Go(func() error {
			for _, v := range input {
				if v == target {
					results <- v
					break
				}
			}
			return nil
		})
	}

	// Wait for the searchers to finish, then signal the collector to stop.
	g.Wait()
	close(results)

	// Now get the final result.
	fmt.Println(s.Wait())
}
Output:
325

func Call added in v0.6.0

func Call[T any](task func() (T, error)) *Single[Result[T]]

Call starts task in a new goroutine. The caller must call Wait to wait for the task to return and collect its result.

func Go added in v0.5.0

func Go[T any](task func() T) *Single[T]

Go runs task in a new goroutine. The caller must call Wait to wait for the task to return and collect its error.

func (*Single[T]) Wait added in v0.5.0

func (s *Single[T]) Wait() T

Wait blocks until the task monitored by s has completed and returns the value it reported.

type Task

type Task func() error

A Task function is the basic unit of work in a Group. Errors reported by tasks are collected and reported by the group.

func NoError added in v0.5.1

func NoError(f func()) Task

NoError adapts f to a Task that executes f and reports a nil error.

Directories

Path Synopsis
examples
copytree command
Binary copytree is an example program to demonstrate the use of the group and throttle packages to manage concurrency.
Binary copytree is an example program to demonstrate the use of the group and throttle packages to manage concurrency.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL