firefly
A collection of high performance concurrent channels.
// create a SPSC channel with a capacity of 2
let = bounded;
spawn;
// receive the message synchronously
assert_eq!;
Channel Flavors
Firefly provides a variety of channel flavors, optimized for specific use cases:
In general, a channel flavor higher up on the list is likely to be more performant than a more generic one lower down.
Bounded channels are created with a bounded capacity; the maximum number of messages that can be held at a given time:
// create a channel that can hold at most 8 messages at a time
let = bounded;
spawn;
// block until messages are sent
while let Ok = rx.recv_blocking
Unbounded channels on the other hand are unlimited in their capacity, meaning that sending never blocks:
// create an unbounded channel
let = unbounded;
spawn;
// block until all messages are sent
while let Ok = rx.recv_blocking
Blocking
Send and receive operations can be performed four different ways:
- Non-blocking (returns immediately with success or failure).
- Asynchronously (blocks the async task).
- Blocking (blocks the thread until the operation succeeds or the channel disconnects).
- Blocking with a timeout (blocks upto a maximum duration of time).
let = bounded;
spawn;
// attempt to receive the message without blocking
match rx.try_recv
// block until the message is sent
assert_eq!;
// block for at most 1 second
match rx.recv_blocking_timeout
// spawn a task that receives the message asynchronously
spawn;
All channels can be used to "bridge" between async and sync code:
let = bounded;
// send messages synchronously
spawn;
// receive asynchronously
spawn;
Disconnection
When all senders or receivers of a given channel are dropped, the channel is disconnected. Any attempts to send a message will fail. Any remaining messages in the channel can be received, but subsequent attempts to receive will also fail:
let = unbounded;
tx.send.unwrap;
tx.send.unwrap;
// disconnect the sender
drop;
// any remaining messages can be received
assert_eq!;
assert_eq!;
// subsequent attempts will error
assert_eq!;