pub struct Queue<T> { /* private fields */ }
Expand description
Main implementation of a multi-producer, multi-consumer (MPMC) asynchronous queue.
This queue allows multiple asynchronous tasks to concurrently send and receive messages. It uses a fixed-size buffer and provides backpressure by waiting when the queue is full (for producers) or empty (for consumers).
§Examples
// Using the legacy Queue API
use tokio_mpmc::Queue;
#[tokio::main]
async fn main() {
// Create a queue with capacity of 100
let queue = Queue::new(100);
// Send a message
if let Err(e) = queue.send("Hello").await {
eprintln!("Send failed: {}", e);
}
// Receive a message
match queue.receive().await {
Ok(Some(msg)) => println!("Received message: {}", msg),
Ok(None) => println!("Queue is empty"),
Err(e) => eprintln!("Receive failed: {}", e),
}
// Close the queue
queue.close();
}
Implementations§
Source§impl<T> Queue<T>
impl<T> Queue<T>
Sourcepub async fn send(&self, value: T) -> QueueResult<()>
pub async fn send(&self, value: T) -> QueueResult<()>
Sends a message value
to the queue.
If the queue is full, the calling task will be suspended until space becomes available or the queue is closed.
§Arguments
value
- The message to send.
§Returns
Ok(())
if the message was successfully sent.
Err(QueueError::QueueClosed)
if the queue was closed while waiting or before sending.
Sourcepub async fn receive(&self) -> QueueResult<Option<T>>
pub async fn receive(&self) -> QueueResult<Option<T>>
Receives a message from the queue.
If the queue is empty, the calling task will be suspended until an item becomes available or the queue is closed.
§Returns
Ok(Some(value))
if a message was successfully received.
Ok(None)
if the queue is closed and empty.
Err(QueueError::QueueClosed)
if the queue was closed while waiting but not empty.
Sourcepub fn close(&self)
pub fn close(&self)
Closes the queue.
This prevents any new messages from being sent. Tasks currently waiting in send
will return Err(QueueError::QueueClosed)
. Tasks waiting in receive
will return
Ok(None)
once the queue is empty.
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Gets the current number of elements in the queue.
§Returns
The number of elements currently in the queue.
Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Checks if the queue is currently empty.
§Returns
true
if the queue contains no elements, false
otherwise.