Function bounded_spsc_queue::make[][src]

pub fn make<T>(capacity: usize) -> (Producer<T>, Consumer<T>)

Creates a new SPSC Queue, returning a Producer and Consumer handle

Capacity specifies the size of the bounded queue to create. Actual memory usage will be capacity.next_power_of_two() * size_of::<T>(), since ringbuffers with power of two sizes are more efficient to operate on (can use a bitwise AND to index into the ring instead of a more expensive modulo operator).

Examples

Here is a simple usage of make, using the queue within the same thread:

// Create a queue with capacity to hold 100 values
let (p, c) = make(100);

// Push `123` onto the queue
p.push(123);

// Pop the value back off
let t = c.pop();
assert!(t == 123);

Of course, a SPSC queue is really only useful if you plan to use it in a multi-threaded environment. The Producer and Consumer can both be sent to a thread, providing a fast, bounded one-way communication channel between those threads:

use std::thread;

let (p, c) = make(500);

// Spawn a new thread and move the Producer into it
thread::spawn(move|| {
  for i in 0..100000 {
    p.push(i as u32);
  }
});

// Back in the first thread, start Pop'ing values off the queue
for i in 0..100000 {
  let t = c.pop();
  assert!(t == i);
}

Panics

If the requested queue size is larger than available memory (e.g. capacity.next_power_of_two() * size_of::<T>() > available memory ), this function will abort with an OOM panic.