Skip to content

JimFawcett/RustBlockingQueue

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

39 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RustBlockingQueue

Documentation

Thread safe queue that blocks dequeuer when empty

Concept:

RustBlockingQueue is a facility for communicating between threads using a thread-safe blocking queue. Note that the Rust message-passing facility does about the same thing.

This is a nice illustration of how to build a data structure that can be shared between threads.

Design:

There is one struct, BlockingQueue<T>, with a few methods in this design:

  #[derive(Debug)]
  pub struct BlockingQueue<T> {
    q: Mutex<VecDeque<T>>,
    cv: Condvar,
  }

  1. new() -> Self
       Create new empty BlockingQueue<T>.
 
  2. en_q(&self, t: T) -> Result<()>
       Push_back t into internal VecDec<T>.
  
  3. de_q(&self) -> Result<T>;
       Pop_front t from internal VecDec<T>.

  4. len(&self) -> usize
       Return number of elements stored in queue.

Sharing between threads is only possible, due to rules of the Rust language, if the shared items are all Mutexes or Condvars, or an aggregate of those, e.g., a tuple, or struct like BlockingQueue.

An instance of BlockingQueue can be shared between threads because it only has two fields and those are share-able. One is a Mutex<VecDeque>, and the other is a Condvar, e.g., a condition variable.

Operation:

Operation is illustrated by the test1.rs in /examples.

Build:

Download and, in a command prompt, use one of the following:

  • cargo build
  • cargo test
  • cargo run --example test1.rs.

About

Thread safe queue that blocks dequeuer when empty

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages