【发布时间】:2020-01-08 13:11:35
【问题描述】:
我想在线程之间共享一个函数引用,但 Rust 编译器说 `dyn for<'r> std::ops::Fn(&'r std::string::String) -> std::string::String` cannot be shared between threads safely。在线程之间共享“常规”值时,我非常了解Send、Sync 和Arc<T>,但在这种情况下,我无法理解问题所在。函数在程序运行时有一个静态地址,所以我在这里看不到问题。
我怎样才能做到这一点?
fn main() {
// pass a function..
do_sth_multithreaded(&append_a);
do_sth_multithreaded(&identity);
}
fn append_a(string: &String) -> String {
let mut string = String::from(string);
string.push('a');
string
}
fn identity(string: &String) -> String {
String::from(string)
}
fn do_sth_multithreaded(transform_fn: &dyn Fn(&String) -> String) {
for i in 0..4 {
let string = format!("{}", i);
thread::spawn(move || {
println!("Thread {}: {}", i, transform_fn(&string))
});
}
}
【问题讨论】:
-
我知道这篇文章。 stackoverflow.com/questions/59442080/… 但我仍然想学习和理解为什么它没有像我想象的那样工作。
-
为什么要使用
&dyn Fn而不是函数指针?do_sth_multithreaded也应该使用闭包吗? -
这还不是要求,不是。也许它可能在未来。
-
我不知道“真正的”函数指针。它适用于这个函数定义
fn do_sth_multithreaded(transform_fn: fn(&String) -> String)- 谢谢!调用如下所示:do_sth_multithreaded(identity);
标签: rust