10 releases (2 stable)
Uses old Rust 2015
2.0.0 | Apr 11, 2021 |
---|---|
1.0.0 | Jul 23, 2020 |
0.4.2 | Apr 23, 2019 |
0.3.0 | Apr 16, 2018 |
0.1.0 | Aug 25, 2017 |
#275 in Memory management
Used in 2 crates
(via havo)
23KB
478 lines
WRC
A thread-safe weighted reference counting smart-pointer for Rust.
Overview
By using weights instead of direct reference counting WRC requires roughly half as many synchronisation operations and writes to the heap. Every time a WRC is cloned its weight is split in two, with half allocated to the parent and half allocated to the child. When a WRC is dropped its weight is removed from the total. When the total weight declines to zero then the referenced object is dropped.
Features
- Thread-safe.
- Efficient.
- Lightweight.
Examples
Sharing some immutable data between threads:
use wrc::Wrc;
use std::thread;
let five = Wrc::new(5);
for _ in 0..10 {
let five = five.clone();
thread::spawn(move || {
println!("{:?}", five);
});
}
Sharing a mutable AtomicUsize
:
use wrc::Wrc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
let val = Wrc::new(AtomicUsize::new(5));
for _ in 0..10 {
let val = val.clone();
thread::spawn(move || {
let v = val.fetch_add(1, Ordering::SeqCst);
println!("{:?}", v);
});
}
Benchmarks
Simple benchmarks have been built using Criterion. Feel free to run cargo bench
to compare them. Each benchmark allocates an owned string and places it within the smart pointer before cloning and dropping the pointer 32 times.
On my machine (2017 13" MacBook Pro, dual-core 2.5GHz i7) I get the following results:
arc 32 time: [470.93 ns 472.80 ns 474.90 ns]
rc 32 time: [161.00 ns 162.08 ns 163.45 ns]
wrc 32 time: [215.32 ns 217.14 ns 219.24 ns]
As expected the algorithm is roughly twice as fast as atomic reference counting, and about 33% slower than standard reference counting making it a good option for projects where a balance between thread safety and performance is required.
License
Source code is licensed under the terms of the MIT license, the text of which is included in the LICENSE file in this distribution.