Rust:dyn Fn()` 不能在线程间安全共享
Rust: dyn Fn()` cannot be shared between threads safely
我在研究 Rust 中的多线程,发现 thread::spawn 中关于使用 Fn 的错误。我的代码是这样的:
use std::thread;
fn print_hello() {
println!("hello");
}
fn run_fn(f: &dyn Fn()) {
let hand = thread::spawn(move || {
f();
});
}
fn main() {
run_fn(&print_hello);
}
编译后出现如下错误:
Compiling fntest v0.1.0 (D:\ray\source\rust\fntest)
error[E0277]: `dyn Fn()` cannot be shared between threads safely
--> src\main.rs:8:16
|
8 | let hand = thread::spawn(move || {
| ^^^^^^^^^^^^^ `dyn Fn()` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `dyn Fn()`
= note: required because of the requirements on the impl of `Send` for `&dyn Fn()`
= note: required because it appears within the type `[closure@src\main.rs:8:30: 10:6]`
note: required by a bound in `spawn`
--> C:\Users\zhang\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\thread\mod.rs:628:8
|
628 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
For more information about this error, try `rustc --explain
E0277`.
error: could not compile `fntest` due to previous error
我该如何解决这个问题?
根据错误说明,您不能使用 &dyn Fn
,因为它不是 Send
。所以,你可以使用一些泛型,限制在这里需要什么,Fn() + Send + 'static
:
use std::thread;
fn print_hello() {
println!("hello");
}
fn run_fn<F: Fn() + Send + 'static>(f: F) {
let _hand = thread::spawn(f);
}
fn main() {
run_fn(&print_hello);
}
我在研究 Rust 中的多线程,发现 thread::spawn 中关于使用 Fn 的错误。我的代码是这样的:
use std::thread;
fn print_hello() {
println!("hello");
}
fn run_fn(f: &dyn Fn()) {
let hand = thread::spawn(move || {
f();
});
}
fn main() {
run_fn(&print_hello);
}
编译后出现如下错误:
Compiling fntest v0.1.0 (D:\ray\source\rust\fntest)
error[E0277]: `dyn Fn()` cannot be shared between threads safely
--> src\main.rs:8:16
|
8 | let hand = thread::spawn(move || {
| ^^^^^^^^^^^^^ `dyn Fn()` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `dyn Fn()`
= note: required because of the requirements on the impl of `Send` for `&dyn Fn()`
= note: required because it appears within the type `[closure@src\main.rs:8:30: 10:6]`
note: required by a bound in `spawn`
--> C:\Users\zhang\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\thread\mod.rs:628:8
|
628 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
For more information about this error, try `rustc --explain
E0277`.
error: could not compile `fntest` due to previous error
我该如何解决这个问题?
根据错误说明,您不能使用 &dyn Fn
,因为它不是 Send
。所以,你可以使用一些泛型,限制在这里需要什么,Fn() + Send + 'static
:
use std::thread;
fn print_hello() {
println!("hello");
}
fn run_fn<F: Fn() + Send + 'static>(f: F) {
let _hand = thread::spawn(f);
}
fn main() {
run_fn(&print_hello);
}