Skip to main content

Module null

Module null 

Source
Expand description

A null flavor type that use to notify thread/future to close

It’s common practice we use () channel in async code, not intended for any message, just subscribe for close event. (For example, cancelling socket operations, stopping worker loops…) This is a module designed for that, with minimized polling cost.

You can initialize a null channel with crate::mpsc::Null::new_async() or crate::mpmc::Null::new_async(), which return a CloseHandle, (which can only be clone or drop, but unable to send any message), and a normal receiver type (which recv method is always blocked until the all copy of CloseHandle is dropped).

NOTE: using mpsc version has less cost then mpmc version.

§Examples

Use null channel to stop a background loop.

use crossfire::{null::CloseHandle, *};
use std::time::Duration;

// Create a null channel
let (stop_tx, stop_rx): (CloseHandle<mpmc::Null>, MAsyncRx<mpmc::Null>)  = mpmc::Null::new().new_async();
let (data_tx, data_rx): (MAsyncTx<mpmc::Array<i32>>, MAsyncRx<mpmc::Array<i32>>) = mpmc::bounded_async::<i32>(10);

// Spawn a background task
let task = tokio::spawn(async move {
    loop {
        tokio::select! {
            // If the null channel is closed (stop_tx dropped), this branch will be selected
            res = stop_rx.recv() => {
                if res.is_err() {
                    println!("Stopping task");
                    break;
                }
            }
            res = data_rx.recv() => {
                match res {
                    Ok(data) => println!("Received data: {}", data),
                    Err(_) => break,
                }
            }
        }
    }
});

data_tx.send(1).await.unwrap();
tokio::time::sleep(Duration::from_millis(10)).await;

// Drop the stop handle to signal the task to stop
drop(stop_tx);

task.await.unwrap();

Structs§

CloseHandle
The CloseHandle is a special type for flavor Null, only impl Clone and Drop
Null
an flavor type can never receive any message