简体   繁体   English

如何将 Arc 克隆传递给闭包?

[英]How to pass an Arc clone to a closure?

I'm trying to write a closure that uses an Arc by cloning it.我正在尝试通过克隆它来编写一个使用Arc的闭包。 Ideally I'd like to have the clone inside the closure, but I'm kinda forced to pass the original Arc , which might be the reason I'm getting the error:理想情况下,我希望在闭包内有克隆,但我有点被迫通过原始Arc ,这可能是我收到错误的原因:

use std::sync::Arc;
use std::sync::Condvar;
use std::sync::Mutex;
use std::collections::VecDeque;

type Fifo<T> = Arc<(Mutex<VecDeque<T>>, Condvar)>;

fn executor(f: Box<dyn Fn()>) {
    f();
}

fn main() {
    let a = Fifo::<u8>::new(
        (Mutex::new(VecDeque::new()), Condvar::new())
    );
    
    let r = Box::new(||{
        let f = a.clone();
        f.0.lock().unwrap().push_back(0);
    });
    executor(r);
}

Error:错误:

error[E0597]: `a` does not live long enough
  --> src/main.rs:19:17
   |
18 |     let r = Box::new(||{
   |                      -- value captured here
19 |         let f = a.clone();
   |                 ^ borrowed value does not live long enough
...
22 |     executor(r);
   |              - cast requires that `a` is borrowed for `'static`
23 | }
   | - `a` dropped here while still borrowed

error: aborting due to previous error

I thought changing to我想改成

let r = Box::new(||{
    //let f = a.clone();
    a.0.lock().unwrap().push_back(0);
});

would force the closure to decide to clone a , therefore fixing the problem, but I get the same error.将迫使闭包决定克隆a ,从而解决问题,但我得到了同样的错误。

How can I pass an Arc to a closure?如何将Arc传递给闭包?

Clone the Arc outside the closure and then move the clone into the closure.在闭包外克隆Arc ,然后move克隆move到闭包中。 Example:例子:

use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Condvar;
use std::sync::Mutex;

type Fifo<T> = Arc<(Mutex<VecDeque<T>>, Condvar)>;

fn executor(f: Box<dyn Fn()>) {
    f();
}

fn main() {
    let a = Fifo::<u8>::new((Mutex::new(VecDeque::new()), Condvar::new()));

    let f = a.clone();
    let r = Box::new(move || {
        f.0.lock().unwrap().push_back(0);
    });

    executor(r);
}

playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM