1 unstable release
new 0.1.0 | Nov 21, 2024 |
---|
#455 in Asynchronous
125 downloads per month
17KB
301 lines
async-oneshot-channel
A simple (<100 lines of logic) "oneshot" channel for asynchronously sending a single value between tasks, in a thread-safe manner. This implementation supports cloned senders while ensuring only one send operation will succeed.
Usage
use futures::executor::block_on;
// Create a new channel
let (tx, rx) = oneshot();
// Send a value
tx.send(42).unwrap();
// Receive the value asynchronously
let result = block_on(rx.recv());
assert_eq!(result, Some(42));
Features
- Multiple senders (through cloning) with guaranteed single-use semantics
- Async support for receiver, instant send.
- Zero unsafe code in the public API, one unsafe line enforcing
MaybeUninit
safety. - Thread-safe: implements
Send
andSync
where appropriate - Cancellation support: receivers get
None
if all senders drop
Licensed under the MIT license.
lib.rs
:
A simple (<100 lines of logic) "oneshot" channel for asynchronously sending a single value between tasks, in a thread-safe manner.
This crate provides a oneshot channel that allows sending a single value from one producer to one consumer. The handle to the sender can be cloned, but only one send operation succeeds. Supports tasks running on different threads.
See crate::oneshot
for more details.
Examples
Basic usage:
use async_oneshot_channel::oneshot;
let (tx, rx) = oneshot();
let result = tx.send(42);
assert!(result.is_ok());
let received = block_on(rx.recv());
assert_eq!(received, Some(42));
Multiple senders (only one succeeds):
let (tx1, rx) = oneshot();
let tx2 = tx1.clone();
// First send succeeds
assert!(tx1.send(1).is_ok());
// Second send fails and returns the value
assert_eq!(tx2.send(2), Err(2));
let received = block_on(rx.recv());
assert_eq!(received, Some(1));
Handling sender drop:
let (tx, rx) = oneshot::<()>();
drop(tx);
// Receiver gets None when all senders are dropped without sending
let received = block_on(rx.recv());
assert_eq!(received, None);
Dependencies
~350KB