0

我正在尝试Arc通过克隆来编写一个使用 an 的闭包。理想情况下,我希望将 clone 放在闭包内,但我有点被迫通过 original 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[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

我想改成

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

将强制关闭决定克隆a,从而解决问题,但我得到同样的错误。

我怎样才能将一个传递Arc给一个闭包?

4

1 回答 1

2

克隆Arc外部封闭,然后move克隆到封闭中。例子:

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

操场

于 2020-12-25T22:00:28.197 回答