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

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

问题描述

我有这样的东西:

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

我明白为什么会这样: clone 之前没有被调用arc 传递给闭包。我可以通过在函数中定义每个闭包并在将 Arc 传递给闭包之前克隆 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()

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;
        });
    }
}

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

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