深拷贝 Rust 中的 Mutex<> 吗?

huangapple go评论67阅读模式
英文:

Deep copies of Mutex<> in Rust?

问题

我必须在循环的每次迭代开始生成一个大的 Vec&lt;Mutex&lt;...&gt;&gt;,并在循环中对其进行修改。由于每次迭代都重新生成它相当昂贵,我正在寻找一种仅初始化向量一次并在循环中进行深层克隆以供使用的方法。当然,简单的 .clone() 不起作用,因为克隆仍然会保护内存中的相同数据,而不是制作其副本。类似以下的东西

let my_vec = (0..big_usize).map(|_| Mutex::new(..)).collect();

for ... {
    clone = my_vec.deep_clone();
    mutate_clone_safely();
}
英文:

I have to generate a large Vec&lt;Mutex&lt;...&gt;&gt; at the start of each iteration in my loop which gets mutated in the loop. Since regenerating it each iteration is quite expensive, I am looking for some way to initialize the vec only once, and make deep clones of the vector to use in the loop. Of course a simple .clone() won't work because the clone will still mutex-guard the same data in memory, not make copies of it. Something along the lines of

let my_vec = (0..big_usize).map(|_| Mutex::new(..)).collect();

for ... {
    clone = my_vec.deep_clone();
    mutate_clone_safely();
}

</details>


# 答案1
**得分**: 4

正如评论中的kmdreko所指出的,你正在寻找的`deep_clone`可以像这样实现:

```rust
fn deep_clone<T: Clone>(v: &[Mutex<T>]) -> Vec<Mutex<T>> {
    v.iter()
        .map(|el| Mutex::new(el.lock().unwrap().clone()))
        .collect()
}

提供了字面回答后,我仍然无法摆脱xy问题的感觉。有人可能合理地问,为什么需要不被任何人共享的互斥锁(因为它们是为本地使用而创建的)。更多信息可能会导致一个明显更好的解决方案。

英文:

As pointed out by kmdreko in the comments, the deep_clone you're looking for could be implemented like this:

fn deep_clone&lt;T: Clone&gt;(v: &amp;[Mutex&lt;T&gt;]) -&gt; Vec&lt;Mutex&lt;T&gt;&gt; {
    v.iter()
        .map(|el| Mutex::new(el.lock().unwrap().clone()))
        .collect()
}

Having provided the literal answer, I still cannot shake off the feeling of xy problem. One might reasonably ask what's the point of mutexes that are not shared by anyone (since they were created for local use). More info might lead to a significantly better solution.

huangapple
  • 本文由 发表于 2023年5月28日 05:12:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定