除了在每个闭包之前克隆它之外,还有其他选择可以在多个闭包中共享 Arc 吗? [英] Is there another option to share an Arc in multiple closures besides cloning it before each closure?

查看:16
本文介绍了除了在每个闭包之前克隆它之外,还有其他选择可以在多个闭包中共享 Arc 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

use std::sync::Arc;

fn main() {
    let arc = Arc::new(42);
    move || { arc.clone() };
    move || { arc.clone() };
}

我得到:

error[E0382]: capture of moved value: `arc`
 --> src/main.rs:6:19
  |
5 |         move || { arc.clone() };
  |         ------- value moved (into closure) here
6 |         move || { arc.clone() };
  |                   ^^^ value captured here after move
  |
  = note: move occurs because `arc` has type `std::sync::Arc<i32>`, which does not implement the `Copy` trait

我明白为什么我会得到这个:在 arc 传递给闭包之前没有调用 clone.我可以通过在函数中定义每个闭包并在将 Arc 传递给闭包之前克隆它来解决这个问题,但还有其他选择吗?

I understand why I am getting this: the clone isn't called before arc is passed to the closure. I can fix this by defining each closure in a function and clone the Arc before passing it to the closure, but is there another option?

推荐答案

没有办法解决.在将 Arc 用于闭包之前,您应该克隆它.常见的模式是将克隆的 Arc 重新绑定到嵌套作用域中的相同名称:

There is no way around it. You should clone the Arc before it is used in a closure. The common pattern is to re-bind the cloned Arc to the same name in a nested scope:

use std::sync::Arc;

fn main() {    
    let arc = Arc::new(42);
    {
        let arc = arc.clone();
        move || { /* do something with arc */ };
    }
    {
        let arc = arc.clone();
        move || { /* do something else with arc */ };
    }
}

这通常与 thread::spawn() 一起完成:

This is usually done together with thread::spawn():

use std::sync::{Arc, Mutex};
use std::thread;

const NUM_THREADS: usize = 4;

fn main() {
    let arc = Arc::new(Mutex::new(42));
    for _ in 0..NUM_THREADS {
        let arc = arc.clone();
        thread::spawn(move || {
            let mut shared_data = arc.lock().unwrap();
            *shared_data += 1;
        });
    }
}

这篇关于除了在每个闭包之前克隆它之外,还有其他选择可以在多个闭包中共享 Arc 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆