tasks

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: BSD-2-Clause Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tasks runs the goroutines of one session as tasks: started, named, canceled and waited for through a Manager, and run one at a time by a Loop.

A pipeline is many goroutines: two per processor, plus whatever the processors start. Left to the Go scheduler they run in parallel and are preempted anywhere, so two of them can interleave between any two statements. A Loop takes that freedom away for the goroutines it runs. Exactly one of its tasks runs at any moment, and it keeps running until it blocks: on a queue, an Event, a timer, the network. What a task does between two such points therefore happens as one step that no other task of the session can observe half done, and tasks made ready are run in the order they were made ready.

Sessions stay independent: each has its own loop, and loops run in parallel on every core. Work that should not hold a session up (inference, encoding, anything that takes real CPU time) is run with Await, which lets the other tasks of the session run meanwhile.

Writing a task

A goroutine becomes a task by being started with Manager.CreateTask. From then on it holds the loop whenever it runs, and the one rule is that it must not block while holding it. Everything that can block goes through this package: wait on an Event or a Queue with the task, and wrap any other blocking call in Await:

var resp *http.Response
tasks.Await(func() { resp, err = client.Do(req) })

A task that blocks without letting go stalls its session, because no other task can run until it returns. Config.StallTimeout reports that with the stack of the task at fault. Never wait for the loop, or block through this package, while holding a mutex another task takes: the task that holds the loop would wait for the mutex, and the mutex's holder for the loop.

A Manager built without a loop starts its tasks as plain goroutines, and every wait here then blocks plainly. Code written against this package runs unchanged with or without a loop.

Experimental

This package is experimental and may change in a minor release.

Index

Constants

View Source
const DefaultStallTimeout = 100 * time.Millisecond

DefaultStallTimeout is how long a task may hold a loop before it is reported, for a loop given no timeout of its own.

Variables

This section is empty.

Functions

func Await

func Await(fn func())

Await is Task.Await for the task the calling goroutine runs, for code that did not keep its task. It just runs fn on a goroutine that is not a task.

func Gather

func Gather(ctx context.Context, fns ...func(ctx context.Context))

Gather runs every fn as a task beside the calling one and returns once they have all returned, letting the other tasks run meanwhile. On a loop the tasks first run in the order they were given.

func Sleep

func Sleep(ctx context.Context, d time.Duration) error

Sleep waits for d or until ctx is done, letting the other tasks run. It returns ctx's error when ctx ended the wait. A sleep of zero lets every task that is ready run and returns.

Types

type Config

type Config struct {
	// StallTimeout is how long one task may hold the loop before it is reported
	// as a stall. Zero uses [DefaultStallTimeout]; a negative value disables
	// the check. A task that holds the loop this long
	// is either blocking without [Await] or computing something that belongs
	// off the loop.
	StallTimeout time.Duration
	// OnStall is called once for each stall, from a goroutine of the loop's
	// own. Nil logs a warning.
	OnStall func(Stall)
}

Config configures a Loop.

type Event

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

Event is a flag tasks wait on: set, cleared, and waited for until set. The zero value is a cleared event.

Setting it makes every waiting task ready, in the order they started waiting. It also works with no loop, and for goroutines that are not tasks, which simply block.

func (*Event) Clear

func (e *Event) Clear()

Clear makes a later wait block again.

func (*Event) IsSet

func (e *Event) IsSet() bool

IsSet reports whether the event is set.

func (*Event) Set

func (e *Event) Set()

Set releases every waiter and lets a later wait pass straight through.

func (*Event) Wait

func (e *Event) Wait(ctx context.Context, t *Task) bool

Wait blocks until the event is set or ctx is done, and reports whether it was set. t is the calling task, or nil when the caller is not one; a caller that did not keep its task passes Current.

func (*Event) WaitFor

func (e *Event) WaitFor(ctx context.Context, t *Task, timeout time.Duration) (set bool, err error)

WaitFor is Event.Wait with a timeout. It reports whether the event was set; when it was not, err tells a timeout (nil) from ctx ending the wait (the context's error).

type Loop

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

Loop runs its tasks one at a time, in the order they become ready. See the package documentation.

func New

func New(cfg Config) *Loop

New returns a loop. Call Loop.Close when the session is over.

func (*Loop) Close

func (l *Loop) Close()

Close stops the loop's watchdog. The tasks are not affected: they end when their functions return.

func (*Loop) Run

func (l *Loop) Run(fn func())

Run runs fn holding the loop and returns when it has. It is how a goroutine that is not a task (a test, an application calling in) does something as one step among the session's tasks.

Called from a task of this loop it just runs fn. Called from a task of another loop it lets go of that loop for as long as it waits and runs, so two sessions calling into each other cannot deadlock.

func (*Loop) Running

func (l *Loop) Running() bool

Running reports whether the calling goroutine is a task of this loop that holds it right now. It is false on a nil loop. It costs about a microsecond and is meant for checks, not for the frame path.

type Manager

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

Manager creates, tracks and cancels the tasks of one session. A pipeline worker makes one and hands it to every processor at setup, so that everything the session runs in the background is started and stopped the same way.

A nil Manager works: it starts its tasks as plain goroutines and tracks nothing.

func NewManager

func NewManager(loop *Loop) *Manager

NewManager returns a manager whose tasks run on loop, one at a time. A nil loop leaves them to run in parallel, as plain goroutines.

func (*Manager) CancelTask

func (m *Manager) CancelTask(ctx context.Context, task *Task, timeout time.Duration) error

CancelTask cancels task and waits for it to finish, letting the other tasks run meanwhile. A timeout of zero waits without a bound; otherwise a task that has not finished in time is logged and left behind.

Canceling the task the call runs on is logged and ignored, since waiting for oneself never ends.

ctx is the caller's own. If it ends while the call waits, the wait is given up and its error returned, so a caller that is itself canceled does not outlive that by waiting here. A ctx that had already ended when the call was made is not a fresh cancellation: the caller is tearing down, and the wait runs to its end so the rest of its cleanup can.

func (*Manager) CreateTask

func (m *Manager) CreateTask(ctx context.Context, name string, fn func(ctx context.Context)) *Task

CreateTask starts fn as a task named name and returns it. fn runs under a context derived from ctx that Manager.CancelTask ends; it should return when that context is done.

A task canceled before it has run at all never runs fn. A panic in fn is logged and ends the task, not the process.

func (*Manager) CurrentTasks

func (m *Manager) CurrentTasks() []*Task

CurrentTasks returns the tasks that have been created and have not finished.

func (*Manager) EventLoop

func (m *Manager) EventLoop() *Loop

EventLoop is the loop this manager's tasks run on, or nil when they run in parallel.

type Mutex

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

Mutex is a mutual exclusion lock a task may hold across a wait. A task that has to wait for it lets the other tasks of its session run meanwhile, where waiting for a sync.Mutex would hold the session up, and deadlock it when the holder is a task of the same session waiting to run again.

Use it only for a lock held across something that waits. State touched between two waits needs no lock among the tasks of one session, and a sync.Mutex held briefly is right for state shared with other goroutines. The zero value is unlocked.

func (*Mutex) Lock

func (m *Mutex) Lock()

Lock locks m, waiting for it off the loop if it is held.

func (*Mutex) TryLock

func (m *Mutex) TryLock() bool

TryLock locks m if it is free and reports whether it did.

func (*Mutex) Unlock

func (m *Mutex) Unlock()

Unlock unlocks m.

type Queue

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

Queue is an unbounded first-in-first-out queue with a single consumer. Putting never blocks, so a slow consumer cannot hold up whoever feeds it. Use NewQueue.

func NewQueue

func NewQueue[T any]() *Queue[T]

NewQueue returns an empty queue.

func (*Queue[T]) Get

func (q *Queue[T]) Get(ctx context.Context, t *Task) (T, bool)

Get returns the next item, waiting for one. It reports false only when ctx ended the wait. t is the calling task, or nil when the caller is not one.

func (*Queue[T]) GetNowait

func (q *Queue[T]) GetNowait() (T, bool)

GetNowait returns the next item without waiting, and reports false when the queue is empty.

func (*Queue[T]) Len

func (q *Queue[T]) Len() int

Len is the number of items waiting.

func (*Queue[T]) Put

func (q *Queue[T]) Put(v T)

Put appends v and wakes the consumer. It never blocks.

type Stall

type Stall struct {
	// Task is the name of the task that holds the loop.
	Task string
	// Held is how long the task had held the loop when the stall was noticed.
	Held time.Duration
	// Stack is the stack of the task's goroutine at that moment, which shows
	// what it is blocked on. It is collected for an OnStall callback, and for
	// the log when the default logger logs at debug level.
	Stack string
}

Stall describes a task that held the loop for longer than Config.StallTimeout.

type Task

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

Task is a goroutine started through a Manager: it has a name, can be canceled, and can be waited for. With a Loop it also takes turns with the other tasks of its session.

The waits of this package take the calling task, which a task gets from Current when it starts. A Task passed to a wait must be the one the calling goroutine runs.

func Current

func Current() *Task

Current returns the task the calling goroutine runs, or nil when it is not a task. It costs about a microsecond, so a task that waits often calls it once when it starts and keeps the result.

func (*Task) Await

func (t *Task) Await(fn func())

Await runs fn, which may block, letting the other tasks of the loop run meanwhile. It returns once fn has returned and the task holds the loop again. It is how a task waits for anything this package has no wait for (a network call, a channel, a lock held for long) and how it runs work that takes real CPU time without holding its session up.

What fn touches is no longer protected by the loop: it runs alongside the session's other tasks, like any goroutine.

On a nil task, one with no loop, or one that has already let go, it just runs fn.

func (*Task) Cancel

func (t *Task) Cancel()

Cancel asks the task to stop by ending the context its function runs under. It does not wait; see Manager.CancelTask.

func (*Task) Done

func (t *Task) Done() <-chan struct{}

Done is closed when the task's function has returned.

func (*Task) Loop

func (t *Task) Loop() *Loop

Loop returns the loop that runs t, or nil when it runs as a plain goroutine.

func (*Task) Name

func (t *Task) Name() string

Name is the name the task was created with. Names are not unique.

func (*Task) Wait

func (t *Task) Wait(ctx context.Context) error

Wait blocks until the task has finished or ctx is done, letting the other tasks run. It returns ctx's error when ctx ended the wait.

func (*Task) Yield

func (t *Task) Yield()

Yield lets every task that is ready run before the caller carries on.

Jump to

Keyboard shortcuts

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