lock_free_freelist/
lib.rs

1//! A fast lock free limited length free list for multiple producer and consumer.
2//! It is meant for cases where consumer is as fast as producer and hence the
3//! limited length of the free list doesn't matter.
4//!
5//! It uses bitmaps of type `usize` to keep track of the free list
6//! and hence free list has a size equal to number of bits in `usize`. If `usize` is `8` bytes then `64`
7//! and if `usize` is `4` bytes then `32`.
8//!
9//! A free list can store free pointers for one type only.
10//! For example,
11//! ```
12//! # use lock_free_freelist::FreeList;
13//! let free_list = FreeList::<Box<i32>>::new(); // a free list for Box<i32>
14//! ```
15//!
16//! # Example
17//!
18//! ```
19//! use lock_free_freelist::{FreeList, Reusable};
20//! use std::{thread, iter};
21//!
22//! #[macro_use]
23//! extern crate lazy_static;
24//!
25//! #[derive(Reusable)]
26//! struct MyType {
27//!     name: String,
28//!     age: u32,
29//! }
30//!
31//! // from https://crates.io/crates/lazy_static
32//! lazy_static! {
33//!     static ref FREE_LIST: FreeList<Box<MyType>> = FreeList::<Box<MyType>>::new();
34//! }
35//!
36//! fn main() {
37//!     // Spawn 4 threads
38//!     // Each thread will allocate elements of type `MyType` using FREE_LIST
39//!     let threads = iter::repeat(0).take(100)
40//!         .map(|_| {
41//!             thread::spawn(|| { for i in 0..1000 {
42//!                 let my_type = MyType { name: "Jane".to_string(), age: 30 };
43//!
44//!                 let mut my_type_on_heap = FREE_LIST.reuse_or_alloc(my_type);
45//!
46//!                 // This is similar to:
47//!                 //      let mut my_type_on_heap = Box::new(my_type);
48//!                 // But when using FREE_LIST.reuse_or_alloc(), the dropped
49//!                 // memory will be reused.
50//!
51//!                 my_type_on_heap.name.push_str(" Doe");
52//!                 my_type_on_heap.age = i;
53//!             }})
54//!         })
55//!         .collect::<Vec<_>>();
56//!
57//!     for handle in threads {
58//!         handle.join().unwrap()
59//!     }
60//! }
61//! ```
62
63mod dump;
64mod free_list;
65mod reusable;
66mod reuse;
67mod smart_pointer;
68
69pub use free_list::FreeList;
70pub use reusable::Reusable;
71pub use reusable_derive::Reusable;
72pub use reuse::Reuse;
73pub use smart_pointer::SmartPointer;