Crates.io | wrc |
lib.rs | wrc |
version | 2.0.0 |
source | src |
created_at | 2017-08-25 10:20:04.375709 |
updated_at | 2021-04-11 21:49:16.977559 |
description | A thread-safe weighted reference counting smart-pointer for Rust. |
homepage | https://gitlab.com/jimsy/wrc |
repository | https://gitlab.com/jimsy/wrc |
max_upload_size | |
id | 28978 |
size | 26,582 |
A thread-safe weighted reference counting smart-pointer for Rust.
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.
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);
});
}
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.
Source code is licensed under the terms of the MIT license, the text of which is included in the LICENSE file in this distribution.