Channels¶
Channel[T] is a thread-safe producer/consumer queue with backpressure, modelled on .NET's
System.Threading.Channels. It works between tasks and between plain threads.
Producer and consumer¶
A bounded channel makes writers wait while it is full, so memory stays bounded however fast the producers are.
writer.complete() ends the consumer's loop once the buffer is drained:
from flpit.channels import Channel
from flpit.task import Task
channel: Channel[int] = Channel.create_bounded(2) # writers wait while 2 items are buffered
async def produce() -> None:
for n in range(5):
await channel.writer.write_async(n) # waits while the channel is full
channel.writer.complete() # no more items: ends the consumer's loop
async def main() -> None:
Task.run(produce)
# read_all_async() is an AsyncFlpIt, so LINQ works on the stream as it arrives.
squares = await (
channel.reader
.read_all_async()
.select(lambda n: n * n)
.to_list()
)
assert squares == [0, 1, 4, 9, 16]
Task.run(main).result()
read_all_async() returns an AsyncFlpIt, so where, select, chunk and the rest work
on the stream as it arrives. reader.completion completes after the last item has been read.
Without waiting¶
try_write and try_read never wait. try_read() returns (True, item) or (False, None):
inbox: Channel[str] = Channel.create_unbounded()
assert inbox.writer.try_write("hello") # never waits
assert inbox.reader.try_read() == (True, "hello")
assert inbox.reader.try_read() == (False, None) # nothing there, and no exception
Dropping instead of waiting¶
When a reader only cares about recent values, such as a sensor feeding a dashboard, let a full channel make room by dropping an item. The writer never waits:
from flpit.channels import BoundedChannelFullMode, BoundedChannelOptions
latest: Channel[int] = Channel.create_bounded(
BoundedChannelOptions(2, full_mode=BoundedChannelFullMode.DROP_OLDEST)
)
for reading in range(1, 6):
latest.writer.try_write(reading) # always succeeds: the oldest item makes room
latest.writer.complete()
assert latest.reader.read_all_async().to_list().result() == [4, 5]
Kinds of channel¶
- Unbounded:
Channel.create_unbounded(). Writes always succeed. - Bounded:
Channel.create_bounded(capacity). Writers wait when it is full, or, withBoundedChannelOptions(capacity, full_mode=...), drop the oldest item (DROP_OLDEST), the newest one in the buffer (DROP_NEWEST), or the item being written (DROP_WRITE). Passitem_dropped=callbacktocreate_boundedto be told about each dropped item. - Rendezvous:
Channel.create_bounded(0). A write completes only when a reader takes the item. - Prioritised:
Channel.create_unbounded_prioritized(). Reads return the smallest item first.
Writing to a completed channel raises ChannelClosedError.
More programs:
examples/channels/.