Task runtime¶
FlpIt includes a lightweight, asyncio-free task runtime for scheduling and coordinating concurrent work,
modelled on the .NET thread pool: synchronous callables and coroutines both run on pooled worker threads.
- Scheduling:
Task.run()schedules coroutines, awaitables, and synchronous callables. - Coordination:
Task.when_all(),Task.when_any()andTask.when_each(), also as query operators. - Cancellation:
CancellationTokenandCancellationTokenSourcesupport cooperative cancellation, callbacks, timeouts, and linked tokens. See Cancellation. - Resource management: configure worker capacity, and shut the runtime down with an observable report.
- Asyncio interoperability: Tasks can be awaited inside asyncio coroutines when
Task.asyncio_interopis enabled (disabled by default).
The runtime starts lazily and manages its own lifecycle. Cancellation of running synchronous functions is cooperative.
Run work in parallel¶
Decorate a blocking function with @task and every call becomes a Task that is already running
(see also mixing sync and async functions).
Task.when_all waits for all of them and returns their results in input order:
from flpit.task import Task, task
@task # a plain blocking function becomes a Task factory
def fetch(page: int, delay: float = 0.1) -> str:
time.sleep(delay)
return f"page {page}"
# Five calls start at once on the worker pool: about 0.1 s in total, not 0.5 s.
pages = Task.when_all([fetch(n) for n in range(5)]).result()
assert pages == ["page 0", "page 1", "page 2", "page 3", "page 4"] # in input order
Take the first result¶
Task.when_any returns the first Task to complete:
winner = Task.when_any(fetch(1, delay=0.5), fetch(2, delay=0.05)).result()
assert winner.result() == "page 2" # the first Task to complete
Handle results as they arrive¶
Task.when_each (.NET Task.WhenEach) is an async stream of tasks in completion order:
async def main() -> None:
tasks = [fetch(1, delay=0.3), fetch(2, delay=0.05)]
# Tasks arrive as they complete, not in input order.
finished = [t.result() async for t in Task.when_each(tasks)]
assert finished == ["page 2", "page 1"]
Task.run(main).result()
Task.collect is the former name and still works.
End a query in the wait¶
when_all(), when_any() and when_each() are also query operators. A query that produces tasks can end in
any of them, so there is no need to wrap it in a Task.when_* call:
from flpit import flp
@task
def nap(seconds: float) -> float:
time.sleep(seconds)
return seconds
# A query of tasks ends in the wait, the same way it would in .NET.
results = flp.it([0.2, 0.1, 0.05]).select(nap).when_all().result() # in query order
first = flp.it([0.5, 0.05]).select(nap).when_any().result() # the first Task to complete
when_any() is the first() of a query of tasks, and when_each() streams them in completion order. .NET has
these only as static Task methods, so the operators are FlpIt's own.
Enumerating the query starts every task before the wait begins. when_any() on an empty query raises
ValueError, and when_all() on an empty query gives an empty list.
Await each result in a query¶
select_await() and where_await() (.NET SelectAwait and WhereAwait) take a callback that returns something
awaitable, usually a Task, and await it for you. They are the ones to use when the callback is a @task
function or a lambda: select() only awaits an async def callback, and a plain callable that returns a Task
would hand you the Task itself.
async def await_each() -> None:
# One at a time, like .NET SelectAwait: nap(0.1) is not called until nap(0.05) has returned.
in_order = await flp.it([0.05, 0.1]).select_await(nap).to_list()
# All at once: select starts the tasks, when_each() hands them over as they finish,
# and select_await awaits each one.
as_finished = await flp.it([0.2, 0.05]).select(nap).when_each().select_await().to_list()
As in .NET, the calls run one at a time. The callback is not called for the next element until the previous result
has arrived, so select_await(nap) on its own is sequential. To run the calls side by side, start the tasks first
with select(), put when_each() in front to take them as they finish, and let select_await() await each one
(the second query above), or end the query in when_all() to get the results in input order.
Without an argument, select_await() awaits the elements themselves, which is what you want after when_each()
or any other query of tasks. It is the same as passing lambda t: t.
Cancel¶
from flpit.task import CancellationTokenSource, OperationCanceledError
cts = CancellationTokenSource()
cts.cancel_after(0.05)
delay = Task.delay(5, token=cts.token)
try:
delay.result()
except OperationCanceledError:
pass
assert delay.status == "cancelled" # cut short after 50 ms
Continue when a task completes¶
continue_with runs a function with the finished task as its argument and returns a new Task. Options such as
TaskContinuationOptions.ONLY_ON_FAULTED or NOT_ON_CANCELED filter when it runs, and token= cancels it:
squared = fetch(3).continue_with(lambda antecedent: len(antecedent.result()))
assert squared.result() == 6 # len("page 3"), computed when fetch(3) completed
Block with a timeout¶
From synchronous code, task.wait(timeout), Task.wait_all(...) and Task.wait_any(...) block with an optional
timeout and token. They return False (wait_any: -1) on timeout and leave the tasks running:
slow = fetch(1, delay=0.3)
assert slow.wait(0.01) is False # timed out; the task keeps running
assert Task.wait_all([slow], timeout=2) # True once everything has completed
Long-running work¶
Blocking work that runs for a long time should not occupy a pool worker:
from flpit.task import TaskCreationOptions
# Blocking work that runs for a long time gets its own thread instead of occupying a pool worker.
dedicated = Task.run(time.sleep, 0.05, creation_options=TaskCreationOptions.LONG_RUNNING)
dedicated.result()
Workers and shutdown¶
Work beyond the worker limit queues up, and workers are added when the pool is starved or blocked in
Task.result(). Calling result() inside a task on a task that has not started yet runs it inline, as .NET does.
Set the limits with Task.configure(min_workers=..., max_workers=...) before the runtime first starts, and stop
the process-wide runtime with Task.shutdown(grace_timeout=..., worker_timeout=...), which returns a report of
work that could not be stopped.
Using asyncio libraries¶
Tasks can be awaited inside asyncio coroutines once Task.asyncio_interop is enabled. It is off by default
because it adds a runtime check to every pending await. Code that depends on an asyncio event loop, such as
httpx.AsyncClient, can run on the pool through the @asyncio_task decorator; see
coro.py. That is an escape hatch and not the
recommended default.
Related¶
More examples¶
The examples/ folder has runnable programs for:
- tasks: awaiting sync functions, async streams with
@async_flpit, cleanup with@await_using - channels, concurrent collections and threading