v2 / vlib / x / async / async.v
35 lines · 30 sloc · 1.36 KB · 15fb60b77ea6073658aa8355b247f2e1ae03b714
Raw
1module async
2
3import context
4
5// JobFn is the function signature run by Group and timeout helpers.
6//
7// The passed context is canceled when the parent context is canceled, when a
8// group task fails, or when a timeout expires. Cancellation is cooperative:
9// jobs should observe `ctx.done()` and return.
10pub type JobFn = fn (mut context.Context) !
11
12// TaskFn is the function signature run by Task.
13//
14// It mirrors JobFn but returns a value. Like all x.async work, the function
15// receives a context and must observe `ctx.done()` for cooperative cancellation.
16pub type TaskFn[T] = fn (mut context.Context) !T
17
18// background returns a root context for async helpers.
19//
20// It is intentionally just a thin wrapper around `context.background()` so code
21// can start with `async.background()` and later pass the same context to the
22// standard `context` APIs without conversion.
23pub fn background() context.Context {
24 return context.background()
25}
26
27// with_cancel returns a cancellable context derived from background.
28//
29// Call the returned cancel function when the surrounding operation is done, even
30// when all jobs completed successfully. That mirrors `context.with_cancel()` and
31// releases parent/child cancellation references promptly.
32pub fn with_cancel() (context.Context, context.CancelFn) {
33 ctx, cancel := new_cancel_context(context.background())
34 return context.Context(ctx), cancel
35}
36