fast-steal 神偷

fast-steal 是一个特别快的多线程库,支持超细颗粒度的任务窃取。
优势
- 只有一个依赖
crossbeam-channel
- 超细颗粒度任务窃取,速度非常快
- 支持各种数字类型,以及各种实现了
Send + Copy + Add<Output = Idx> + Sub<Output = Idx> + Mul<Output = Idx> + Div<Output = Idx> + Sum<Idx> + Ord + PartialEq 的类型
- 尽可能少的 clone
- 安全的 Rust 代码
使用方法
use fast_steal::{spawn::Spawn, split_task::SplitTask};
use std::collections::{HashMap, hash_map::Entry};
fn fib(n: u128) -> u128 {
match n {
0 => 0,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}
fn fib_fast(n: u128) -> u128 {
let mut a = 0;
let mut b = 1;
for _ in 0..n {
(a, b) = (b, a + b);
}
a
}
fn main() {
let tasks = vec![(0..44).into()];
let task_group = tasks.split_task(8);
let (tx, rx) = crossbeam_channel::unbounded();
let handle = task_group.spawn(move |rx_task, id, progress| {
println!("线程 {id} 启动");
'task: for tasks in &rx_task {
if tasks.is_empty() {
break;
}
for task in tasks {
for i in task.start..task.end {
if !rx_task.is_empty() {
continue 'task;
}
progress(1);
let res = fib(i);
tx.send((i, res)).unwrap();
}
}
}
});
let mut data = HashMap::new();
for (i, res) in rx {
match data.entry(i) {
Entry::Occupied(_) => panic!("数字 {i},值为 {res} 重复计算"),
Entry::Vacant(entry) => {
entry.insert(res);
}
}
}
handle.join().unwrap();
dbg!(&data);
for i in tasks[0].start..tasks.last().unwrap().end {
assert_eq!((i, data.get(&i)), (i, Some(&fib_fast(i))));
}
}