Threading primitives¶
flpit.threading adds the .NET threading primitives that go with the task runtime.
SemaphoreSlim¶
A semaphore limits how many callers are inside a section at once. The same instance works from plain threads
(wait()) and from tasks (await wait_async()), and asynchronous waiters are served in first-in, first-out
order.
from flpit.task import Task
from flpit.threading import SemaphoreSlim
throttle = SemaphoreSlim(2) # at most two at a time
def limited_work() -> None:
throttle.wait() # blocks until a slot is free
try:
time.sleep(0.05)
finally:
throttle.release() # always give the slot back
start = time.perf_counter()
Task.wait_all([Task.run(limited_work) for _ in range(6)])
# Six 50 ms jobs, two at a time, need at least three rounds (0.14 leaves slack for the timer).
assert time.perf_counter() - start >= 0.14
async def fetch(n: int) -> int:
await throttle.wait_async() # the awaitable counterpart of wait()
try:
return n * 2
finally:
throttle.release()
assert Task.run(fetch, 21).result() == 42
Always release in a finally block, so a failure gives the slot back.
Warning
with throttle: does not acquire the semaphore. As C#'s using, it disposes it when the block ends.
Use wait() or wait_async() with release().
wait and wait_async take a timeout in seconds (or a timedelta) and a CancellationToken. They return False
on timeout, and raise OperationCanceledError when the token is cancelled.
current_count reports the free slots.
ThreadLocal¶
ThreadLocal[T] keeps one value per OS thread, created lazily by a factory:
from flpit.threading import ThreadLocal
counter = ThreadLocal(lambda: 0) # each thread starts with its own 0
counter.value += 1
assert Task.run(lambda: counter.value).result() == 0 # a pool thread does not see this thread's value
assert counter.value == 1
A coroutine that resumes on another pool worker after an await sees that worker's value. For values that follow
the task instead, use AsyncLocal. ThreadLocal(factory, track_all_values=True) makes values list
every thread's value.
AsyncLocal¶
AsyncLocal[T] keeps a value with the logical flow of a task, however many pool workers it hops between. Typical
uses are a request ID or user context that is set once and read further down the call chain:
from flpit.threading import AsyncLocal
request_id = AsyncLocal[str]()
async def handle(rid: str) -> str:
request_id.value = rid # set once ...
await Task.delay(0.02) # ... the task may resume on another pool worker
return request_id.value # ... and still sees its own value
async def serve() -> None:
request_id.value = "main"
a, b = Task.run(handle, "a"), Task.run(handle, "b")
assert await Task.when_all(a, b) == ["a", "b"] # each task kept its own value
assert request_id.value == "main" # and nothing leaked back
Task.run(serve).result()
A task inherits the value of the flow that started it. Changes made inside the task do not reach its parent.
AsyncLocal is built on contextvars.ContextVar, and an optional value_changed_handler is called when the value
changes.
ManualResetEvent¶
ManualResetEvent is a signal that stays set until it is reset. Threads wait on it with wait_one(), and one
set() releases all of them until reset() is called:
from flpit.threading import ManualResetEvent
start = ManualResetEvent() # not signaled yet
started: list[int] = []
def runner(n: int) -> None:
start.wait_one() # blocks until the event is set
started.append(n)
runners = [Task.run(runner, n) for n in range(3)]
time.sleep(0.05)
assert started == [] # everyone is still waiting
start.set() # one signal releases all of them
Task.wait_all(runners)
assert sorted(started) == [0, 1, 2]
start.reset()
assert start.wait_one(0.01) is False # unsignaled again: a wait with a timeout gives up
wait_one(timeout) returns False when the timeout elapses first. It blocks the calling thread, so inside a task it
occupies a pool worker while it waits.
More programs:
examples/threading/.