当前位置:网站首页>【crossbeam系列】5 crossbeam-util和crossbeam-queue:一些实用的小东西
【crossbeam系列】5 crossbeam-util和crossbeam-queue:一些实用的小东西
2022-06-29 15:36:00 【51CTO】
这一次我们来介绍一下crossbeam-util和crossbeam-queue,中的一些东西和用法。
crossbeam-util
AtomicCell
这个是并发版的std::cell::Cell,可以对&self就起到变更内部值的效果,主要会用到下面三个方法:
use crossbeam_utils::atomic::AtomicCell;
let a = AtomicCell::new(7);
assert_eq!(a.load(), 7);
assert_eq!(a.swap(8), 7);
assert_eq!(a.load(), 8);
a.store(9);
assert_eq!(a.load(), 9);
ShardedLock
这个和std::sync::RwLock功能相同,不过相对来说读会更快而写更慢。大家在实际使用时可以根据业务的特点酌情选择。
use crossbeam_utils::sync::ShardedLock;
let lock = ShardedLock::new(5);
// 读的锁可以同时获取
{
let r1 = lock.read().unwrap();
let r2 = lock.read().unwrap();
assert_eq!(*r1, 5);
assert_eq!(*r2, 5);
}
// 写的锁只能有一个
{
letmut w = lock.write().unwrap();
*w += 1;
assert_eq!(*w, 6);
}
WaitGroup
这个类似Golang中的sync.WaitGroup,可以用来等待几个线程的工作全部完成。
use crossbeam_utils::sync::WaitGroup;
use std::thread;
// 创建新的等待组
let wg = WaitGroup::new();
for _ in0..4 {
// 创建等待组的引用
let wg = wg.clone();
thread::spawn(move || {
// 实际逻辑
// 解除对等待组的引用
drop(wg);
});
}
// 会阻塞直到所有线程完成工作
wg.wait();
注意和std::sync::Barrier不同的是,WaitGroup中的线程数量是动态的。
scope
这个和std::thread比较像,不同点在于能够支持对当前堆栈的引用。比如如果我们想要写如下的代码
let array = [1, 2, 3];
letmut guards = vec![];
for i in &array {
let guard = std::thread::spawn(move || {
println!("element: {}", i);
});
guards.push(guard);
}
for guard in guards {
guard.join().unwrap();
}
是会报错的,因为编译器会要求&array具有'static的生命周期。但实际上因为join的部分,所以其实不会有问题,但编译器并不知道。于是就有了scope的用武之地。有了scope可以这么写:
let array = [1, 2, 3];
crossbeam::scope(|scope| {
for i in &array {
scope.spawn(move || {
println!("element: {}", i);
});
}
});
是不是有时候比thread要更方便一些呢~
crossbeam-queue
这是并发版的队列,其实可以理解为实现了send和sync的队列。分为容量有限的ArrayQueue
use crossbeam_queue::{ArrayQueue, PushError};
let q = ArrayQueue::new(2); // 指定容量为2
assert_eq!(q.push('a'), Ok(()));
assert_eq!(q.push('b'), Ok(()));
assert_eq!(q.push('c'), Err(PushError('c')));
assert_eq!(q.pop(), Ok('a'));
和容量无限的SegQueue
use crossbeam_queue::{PopError, SegQueue};
let q = SegQueue::new();
q.push('a');
q.push('b');
assert_eq!(q.pop(), Ok('a'));
assert_eq!(q.pop(), Ok('b'));
assert_eq!(q.pop(), Err(PopError));
当然容量无限的代价是需要动态增加容量,这也使得SegQueue的性能会低一些。crossbeam-queue就这些内容了,是不是很简单~
小结
其实util里面还有一些东西这里没有讲,大家可以自己去看看。这期讲的都是一些零碎的小东西。我们的crossbeam系列到这一期就结束了?吗?也许下期还有,敬请期待~
边栏推荐
- The role of each layer in convolutional neural network
- Summary of recent work
- 2022 OpenVINO DevCon 大揭秘!英特尔携众多合作伙伴深化开发者生态建设,释放AI产业创新潜能
- MySQL development specification pdf
- 11.应用层数据传输格式/端口号-bite
- El table column row button anti weight control loading
- C language homework - matching system
- LeetCode-1188. Designing finite blocking queues
- Imgutil image processing tool class, text extraction, image watermarking
- File常用工具類, 流相關運用 (記錄)
猜你喜欢

C#学习一:值类型与引用类型

Paging SQL (rownum, row_number, deny_rank, rank)

Leetcode-470- implement rand10() with rand7()

three.js和高德地图结合引入obj格式模型-效果演示

Huawei cloud AOM version 2.0 release

EasyGBS调用获取实时快照接口时,出现白色方块该如何解决?

PostgreSQL source code learning (23) -- transaction log ④ - log assembly

Mingdeyang xilinx-k7-325t/410t core board data manual

GWD: rotating target detection based on Gaussian Wasserstein distance | ICML 2021

智能聊天机器人的优势在哪里?资深独立站卖家告诉你!
随机推荐
. Net program configuration file operation (INI, CFG, config)
TDesign, which gave us benefits last time, will tell us its open source story today
MySQL development specification pdf
MySQL scheduled full database backup & rolling deletion of backup data before the specified date
欧标插头EN50075测试项目
Basic composition of radar
Flink SQL任务TaskManager内存设置
再也不用担心窗体变形了
如何用好数据科学?
李飞飞划重点的「具身智能」,走到哪一步了?
Numpy 的研究仿制 1
PostgreSQL source code learning (23) -- transaction log ④ - log assembly
11.应用层数据传输格式/端口号-bite
Leetcode-64- minimum path sum
C # learning 1: value type and reference type
Mysql database naming conventions PDF
What are the advantages of intelligent chat robots? Senior independent station sellers tell you!
File常用工具类, 流相关运用 (记录)
89.(cesium篇)cesium聚合图(自定义图片)
wallys/m.2/Adapter card(one pcie1x to 4 x Mini PCIE)