我想将命令(闭包)发送到不同的线程,闭包捕获非Sync
变量(因此我不能"分享"带有Arc
的闭包,如Can you clone a closure?中所述。
闭包只捕获实现Clone
的元素,所以我觉得闭包也可以派生Clone
。
#![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`
当前语法中有什么方法可以实现/派生闭包的特征吗?
对此的一个肮脏的解决方法是(手动)定义包含所需环境的结构,实现Clone
,并定义FnOnce
或Invoke
特征。
答案 0 :(得分:2)
Box<dyn FnOnce>
稳定。您的代码现在可以在稳定的Rust中运行,如果您将其更改为仅在克隆后将其封闭:
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
这不能回答你的直接问题,但是在关闭变量之前克隆你的变量是否可行?
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();
}
您甚至可以将此逻辑提取到“工厂”功能中。
让我们深入了解一下。首先,我们认识到Box<FnBox>
是特征对象,克隆它们有点困难。根据{{3}}中的答案,并使用较小的案例,我们最终得到:
#![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();
}
值得注意的是,我们必须引入一个特征来实现克隆和另一个特征,将克隆特征与FnBox
结合起来。
然后,“只是”为MyFnBox
的所有实施者实施FnBox
并启用另一个夜间功能:#![clone_closures]
(预定为How to clone a struct storing a boxed trait object?):
#![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 ...
}