Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: dyn Fn()` cannot be shared between threads safely

I study multithreads in Rust, find an error about use Fn in thread::spawn. My code like this:

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

After compiling, I get the following error:

   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 

How can I resolve this issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As per the error note, you cannot use &dyn Fn because it is not Send. So, you could use some generics, constrained to what it is needed here, 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);
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading