Broadcast¤
A channel that delivers all messages to all receivers.
Description¤
BroadcastChannels can have multiple
senders and multiple
receivers. Each message sent through
any of the senders will be received by all receivers.
Characteristics
- Buffered: Yes, with one buffer per receiver
- Buffer full policy: Drop oldest message
- Multiple receivers: Yes
- Multiple senders: Yes
- Thread-safe: No
This channel is buffered, and when messages are not being consumed fast enough and the buffer fills up, old messages will get dropped.
Each receiver has its own buffer, so messages will only be dropped for receivers that can't keep up with the senders, and not for the whole channel.
Instantiating this class creates a new broadcast channel, and returns an
initial sender and receiver. Further senders and receivers can be created
with the BroadcastSender.clone()
and
BroadcastSender.subscribe()
methods respectively.
When a sender or a receiver is not needed anymore, it should be closed with
BroadcastSender.aclose() or
BroadcastReceiver.close().
The channel closes itself when all its senders are closed. This is what each side sees:
-
As soon as all senders are closed, the channel is closed. Receivers can still drain the messages pending in their buffers, but after that,
receive()raises aReceiverStoppedError, andasync forloops over them end. -
While all receivers are closed or garbage-collected,
send()drops the message and raises aSenderHasNoReceiversError. The channel stays open, so oncesubscribe()creates a new receiver, sending works again. Withresend_latest=True, that receiver first gets the last message sent, unless it wasNone, even ifsend()raised.
Senders can check
has_receivers to stop
producing messages that nobody would receive, and receivers can check
has_senders to find out
whether new messages can still arrive.
Tip
Close every sender, also when a task fails, for example with
async with contextlib.aclosing(sender):. A sender that is never closed keeps
the channel open, even if it was garbage-collected, and its receivers keep
waiting for messages.
Close the initial receiver if it isn't needed, instead of binding it to _.
Until _ is reassigned or goes out of scope, that receiver stays attached:
has_receivers stays
True, and the receiver's buffer fills up.
This channel is useful, for example, to implement a pub/sub pattern, where multiple consumers can subscribe to a channel to receive all messages.
Examples¤
Send a few numbers to a receiver
This is a very simple example that sends a few numbers from a single sender to a single receiver. The receiver stops when the sender is closed.
import asyncio
from frequenz.channels import BroadcastChannel, Receiver, Sender
async def send(sender: Sender[int]) -> None:
for message in range(3):
print(f"sending {message}")
await sender.send(message)
await sender.aclose()
async def receive(receiver: Receiver[int]) -> None:
async for message in receiver:
print(f"received {message}")
print("all senders are closed")
async def main() -> None:
sender, receiver = BroadcastChannel[int](name="numbers")
async with asyncio.TaskGroup() as task_group:
task_group.create_task(send(sender))
task_group.create_task(receive(receiver))
asyncio.run(main())
The output should look something like (although the sending and received might appear more interleaved):
Send a few numbers from multiple senders to multiple receivers
This is a more complex example that sends a few numbers from multiple senders to multiple receivers. The receivers stop when all senders are closed.
import asyncio
from frequenz.channels import BroadcastChannel, Receiver, Sender
async def send(name: str, sender: Sender[int], start: int, stop: int) -> None:
for message in range(start, stop):
print(f"{name} sending {message}")
await sender.send(message)
await sender.aclose()
async def receive(name: str, receiver: Receiver[int]) -> None:
async for message in receiver:
print(f"{name} received {message}")
await asyncio.sleep(0.1) # sleep (or work) with the data
async def main() -> None:
sender_1, receiver_1 = BroadcastChannel[int](name="numbers")
sender_2 = sender_1.clone()
receiver_2 = sender_1.subscribe()
async with asyncio.TaskGroup() as task_group:
task_group.create_task(send("sender_1", sender_1, 10, 13))
task_group.create_task(send("sender_2", sender_2, 20, 22))
task_group.create_task(receive("receiver_1", receiver_1))
task_group.create_task(receive("receiver_2", receiver_2))
asyncio.run(main())
The output should look something like this (although the sending and received might appear interleaved in a different way):
sender_1 sending 10
sender_1 sending 11
sender_1 sending 12
sender_2 sending 20
sender_2 sending 21
receiver_1 received 10
receiver_2 received 10
receiver_1 received 11
receiver_2 received 11
receiver_1 received 12
receiver_2 received 12
receiver_1 received 20
receiver_2 received 20
receiver_1 received 21
receiver_2 received 21
Stop producing messages when nobody is listening
This example produces messages only for as long as there are receivers to receive them.
import asyncio
from frequenz.channels import BroadcastChannel, BroadcastSender, Receiver
async def produce(sender: BroadcastSender[int]) -> None:
counter = 0
while sender.has_receivers:
await sender.send(counter)
counter += 1
await asyncio.sleep(0.1) # wait for (or compute) the next message
print(f"no receivers left, stopping after {counter} messages")
await sender.aclose()
async def consume(receiver: Receiver[int]) -> None:
for _ in range(3):
print(f"received {await receiver.receive()}")
receiver.close()
async def main() -> None:
sender, receiver = BroadcastChannel[int](name="numbers")
async with asyncio.TaskGroup() as task_group:
task_group.create_task(produce(sender))
task_group.create_task(consume(receiver))
asyncio.run(main())
The output should be: