rust - 有没有办法将 "check and set"的值设为 `std::cell::Cell` ?

标签 rust llvm atomic

我一直在寻找可以编译成神奇的 cmpxchg 的东西操作说明。深入了解后 文档,我找不到任何可以为 Cell 完成此操作的内容.

也许这是一个反模式?

代码:

深入研究代码后,我将以下内容添加到 Cell 的实现中,看看它是否可行。

pub fn cmp_and_set(&self, old: T, new: T) -> T {
    unsafe {
        ::intrinsics::atomic_cxchg(self.value.get(), old, new)
    }
}
// ^ there are many many reasons why this is not so great
// this is just an example of what I'm looking for

简单用法

fn main() {
    let c0 = Cell::new(10);
    let val0 = c0.cmp_and_set(11, 5);
    assert_eq!(c0.get(), 5);
    let val1 = c0.cmp_and_set(10, 42);
    assert_eq!(c0.get(), 42);
}

据我所知,对于非常基本的情况它是有效的,但是同样有很多原因导致特定的实现不那么出色。 事实上,我编辑了标准库以获得我正在寻找的东西,这意味着我肯定在尝试实现某种反模式。

背景:

这是重新阅读 The Rust Programming Language 中的以下内容时提示的

It is still possible to violate your own invariants using this wrapper, so be careful when using it. If a field is wrapped in Cell, it's a nice indicator that the chunk of data is mutable and may not stay the same between the time you first read it and when you intend to use it.

最佳答案

TL;DR:不,没有,因为没有必要。


Compare and Set 仅在两个(或更多)参与者并行修改对象时才有值(value)。

虽然 Cell 允许内部可变性,但它不是线程安全的,因此您永远不会遇到两个参与者试图并行修改它的情况。

因此,您可以只使用get()、比较和set(),如果它适合您的话。如果您不自己调用其他代码,则没有人会更改您的 get()set() 之间的值。

关于rust - 有没有办法将 "check and set"的值设为 `std::cell::Cell` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582847/

相关文章:

command-line - 如何通过 Clap 将所有命令行参数传递给另一个程序?

c++ - AddressSanitizer GCC 4.8 双重释放错误

asynchronous - Rust lazy_static 与 async/await?

assembly - 是否可以直接使用 LLVM-assembly?

optimization - 我如何查看 LLVM 的 opt 使用了哪些优化过程?

compiler-construction - LLVM 无操作指令?

objective-c - 在 Objective C 中使用原子属性 : Any side effects?

database - PostgreSQL 多行插入是全有还是全无?

graph - 拥有的arena数据结构

rust - 一次映射一个迭代器 n 个项目