当 FnBox 闭包无法放入 Arc 时,如何克隆它? [英] How can I clone a FnBox closure when it cannot be put into an Arc?

查看:77
本文介绍了当 FnBox 闭包无法放入 Arc 时,如何克隆它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向不同的线程发送命令(闭包),闭包捕获一个非 Sync 变量(因此我不能用 Arc,如你能克隆一个闭包吗?).

I would like to send commands (closures) to different threads, with the closure capturing a non-Sync variable (therefore I cannot "share" the closure with an Arc, as explained in Can you clone a closure?).

闭包只捕获实现Clone的元素,所以我觉得闭包也可以派生Clone.

The closure only captures elements which implement Clone, so I would feel that the closure could derive Clone as well.

#![feature(fnbox)]

use std::boxed::FnBox;
use std::sync::mpsc::{self, Sender};
use std::thread;

type Command = Box<FnBox(&mut SenderWrapper) + Send>;

struct SenderWrapper {
    tx: Option<Sender<u64>>,
}
impl SenderWrapper {
    fn new() -> SenderWrapper {
        SenderWrapper { tx: None }
    }
}

fn main() {
    let (responses_tx, responses_rx) = mpsc::channel();
    let closure: Command = Box::new(move |snd: &mut SenderWrapper| {
        snd.tx = Some(responses_tx); // Captures tx, which is not Sync but is Clone
    });

    let mut commands = Vec::new();
    for i in 0..2i32 {
        let (commands_tx, commands_rx) = mpsc::channel();
        commands.push(commands_tx);
        thread::spawn(move || {
            let mut wrapper = SenderWrapper::new();
            let command: Command = commands_rx.recv().unwrap();
            command.call_box((&mut wrapper,));
            // Continue ...
        });
    }

    for tx in commands.iter() {
        commands[0].send(closure.clone()).unwrap(); // How can I make this clone() work?
    }
    // use answers ...
}

error[E0599]: no method named `clone` found for type `std::boxed::Box<for<'r> std::boxed::FnBox<(&'r mut SenderWrapper,), Output=()> + 'static>` in the current scope
  --> src/main.rs:40:34
   |
40 |         commands[0].send(closure.clone()).unwrap();
   |                                  ^^^^^
   |
   = note: the method `clone` exists but the following trait bounds were not satisfied:
           `std::boxed::Box<for<'r> std::boxed::FnBox<(&'r mut SenderWrapper,), Output=()>> : std::clone::Clone`

在当前的语法中有什么方法可以为闭包实现/派生特征吗?

Is there any way in the current syntax where we can implement / derive traits for closures?

一个肮脏的解决方法是(手动)定义一个包含所需环境的结构,实现 Clone,并定义 FnOnceInvoke 特质.

A dirty workaround for this would be to define (by hand) a structure containing the required environment, implement Clone, and define the FnOnce or Invoke trait.

推荐答案

Rust 1.35

Box 是稳定的.如果您将代码更改为仅在克隆后装箱闭包,您的代码现在可以在稳定的 Rust 中运行:

Rust 1.35

Box<dyn FnOnce> is stable. Your code now works in stable Rust if you change it to only box the closure after cloning it:

use std::sync::mpsc::{self, Sender};
use std::thread;

type Command = Box<FnOnce(&mut SenderWrapper) + Send>;

struct SenderWrapper {
    tx: Option<Sender<u64>>,
}
impl SenderWrapper {
    fn new() -> SenderWrapper {
        SenderWrapper { tx: None }
    }
}

fn main() {
    let (responses_tx, responses_rx) = mpsc::channel();
    let closure = move |snd: &mut SenderWrapper| {
        snd.tx = Some(responses_tx); // Captures tx, which is not Sync but is Clone
    };

    let mut commands = Vec::new();
    for i in 0..2i32 {
        let (commands_tx, commands_rx) = mpsc::channel();
        commands.push(commands_tx);
        thread::spawn(move || {
            let mut wrapper = SenderWrapper::new();
            let command: Command = commands_rx.recv().unwrap();
            command(&mut wrapper);
            // Continue ...
        });
    }

    for tx in commands.iter() {
        tx.send(Box::new(closure.clone())).unwrap(); // How can I make this clone() work?
    }
    // use answers ...
}

另见:

闭包现在实现了Clone

这不能回答您的直接问题,但是在闭包中捕获变量之前克隆变量是否可行?

This doesn't answer your direct question, but is it feasible to just clone your variables before capturing them in the closure?

for tx in commands.iter() {
    let my_resp_tx = responses_tx.clone();
    let closure = Box::new(move |snd: &mut SenderWrapper| {
        snd.tx = Some(my_resp_tx);
    });
    commands[0].send(closure).unwrap();
}

您甚至可以将此逻辑提取到工厂"函数中.

You can even extract this logic into a "factory" function.

让我们深入了解一下.首先,我们认识到 Box 是一个 trait 对象,克隆它们有点困难.按照如何克隆存储装箱特征对象的结构?中的答案,并使用较小的案例,我们最终得到:

Let's take a deeper look. First, we recognize that Box<FnBox> is a trait object, and cloning those is kind of difficult. Following the answers in How to clone a struct storing a boxed trait object?, and using a smaller case, we end up with:

#![feature(fnbox)]

use std::boxed::FnBox;

type Command = Box<MyFnBox<Output = ()> + Send>;

trait MyFnBox: FnBox(&mut u8) + CloneMyFnBox {}

trait CloneMyFnBox {
    fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send>;
}

impl<T> CloneMyFnBox for T
where
    T: 'static + MyFnBox + Clone + Send,
{
    fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send> {
        Box::new(self.clone())
    }
}

impl Clone for Box<MyFnBox<Output = ()> + Send> {
    fn clone(&self) -> Box<MyFnBox<Output = ()> + Send> {
        self.clone_boxed_trait_object()
    }
}

fn create() -> Command {
    unimplemented!()
}

fn main() {
    let c = create();
    c.clone();
}

值得注意的是,我们必须引入一个 trait 来实现克隆,另一个 trait 将克隆 trait 与 FnBox 结合起来.

Of note is that we had to introduce a trait to implement cloning and another trait to combine the cloning trait with FnBox.

然后只是"为 FnBox 的所有实现者实现 MyFnBox 并启用另一个夜间功能:#![clone_closures](预定用于 Rust 1.28 中的稳定):

Then it's "just" a matter of implementing MyFnBox for all implementors of FnBox and enabling another nightly feature: #![clone_closures] (slated for stabilization in Rust 1.28):

#![feature(fnbox)]
#![feature(clone_closures)]

use std::boxed::FnBox;
use std::sync::mpsc::{self, Sender};
use std::thread;

struct SenderWrapper {
    tx: Option<Sender<u64>>,
}
impl SenderWrapper {
    fn new() -> SenderWrapper {
        SenderWrapper { tx: None }
    }
}

type Command = Box<MyFnBox<Output = ()> + Send>;

trait MyFnBox: FnBox(&mut SenderWrapper) + CloneMyFnBox {}

impl<T> MyFnBox for T
where
    T: 'static + FnBox(&mut SenderWrapper) + Clone + Send,
{
}

trait CloneMyFnBox {
    fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send>;
}

impl<T> CloneMyFnBox for T
where
    T: 'static + MyFnBox + Clone + Send,
{
    fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send> {
        Box::new(self.clone())
    }
}

impl Clone for Box<MyFnBox<Output = ()> + Send> {
    fn clone(&self) -> Box<MyFnBox<Output = ()> + Send> {
        self.clone_boxed_trait_object()
    }
}

fn main() {
    let (responses_tx, responses_rx) = mpsc::channel();
    let closure: Command = Box::new(move |snd: &mut SenderWrapper| {
        snd.tx = Some(responses_tx);
    });

    let mut commands = Vec::new();
    for i in 0..2i32 {
        let (commands_tx, commands_rx) = mpsc::channel();
        commands.push(commands_tx);
        thread::spawn(move || {
            let mut wrapper = SenderWrapper::new();
            let command: Command = commands_rx.recv().unwrap();
            command.call_box((&mut wrapper,));
            // Continue ...
        });
    }

    for tx in commands.iter() {
        commands[0].send(closure.clone()).unwrap(); // How can I make this clone() work?
    }
    // use answers ...
}

这篇关于当 FnBox 闭包无法放入 Arc 时,如何克隆它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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