英文:
Deep copies of Mutex<> in Rust?
问题
我必须在循环的每次迭代开始生成一个大的 Vec<Mutex<...>>
,并在循环中对其进行修改。由于每次迭代都重新生成它相当昂贵,我正在寻找一种仅初始化向量一次并在循环中进行深层克隆以供使用的方法。当然,简单的 .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<Mutex<...>>
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<T: Clone>(v: &[Mutex<T>]) -> Vec<Mutex<T>> {
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论