Function ring_channel::ring_channel[][src]

pub fn ring_channel<T>(
    capacity: NonZeroUsize
) -> (RingSender<T>, RingReceiver<T>)

Opens a multi-producer multi-consumer channel backed by a ring buffer.

The associated ring buffer can contain up to capacity pending messages.

Sending and receiving messages through this channel never blocks, however pending messages may be overwritten if the internal ring buffer overflows.

Panics

Panics if the capacity is 0.

Examples

use ring_channel::*;
use std::num::NonZeroUsize;
use std::thread;
use std::time::{Duration, Instant};

// Open a channel to transmit the time elapsed since the beginning of the countdown.
// We only need a buffer of size 1, since we're only interested in the current value.
let (mut tx, mut rx) = ring_channel(NonZeroUsize::new(1).unwrap());

thread::spawn(move || {
    let countdown = Instant::now() + Duration::from_secs(10);

    // Update the channel with the time elapsed so far.
    while let Ok(_) = tx.send(countdown - Instant::now()) {

        // We only need millisecond precision.
        thread::sleep(Duration::from_millis(1));

        if Instant::now() > countdown {
            break;
        }
    }
});

loop {
    match rx.recv() {
        // Print the current time elapsed.
        Ok(timer) => {
            print!("\r{:02}.{:03}", timer.as_secs(), timer.as_millis() % 1000);

            if timer <= Duration::from_millis(6600) {
                print!(" - Main engine start                           ");
            } else {
                print!(" - Activate main engine hydrogen burnoff system");
            }
        }

        Err(RecvError::Disconnected) => break,
    }
}

println!("\r00.0000 - Solid rocket booster ignition and liftoff!")