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

How to pass arguments to a thread in rust?

I have a closure which I cannot change, which I need to run in a new thread and to which I need to pass a variable. This is how I imagine the code to look like:

use std::thread;

fn main() {
    // I can not influence this closure, but this is what it looks like
    let handle = move |data: i32| {
        println!("Got {data}")
    };

    let foo = 123;
    // This doesn't work
    thread::spawn(handle).arg(foo).join()
}

Equivalent code in Python is does work so I am wondering whether this is possible in rust and if so then how.

Thank you in advance.

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 :

The documentation for thread::spawn() indicates it expects as input a closure with no arguments. Therefore, you can’t directly use your handle closure. However, you can create a new closure with no arguments that calls your handle closure like so:

use std::thread;

fn main() {

    let handle = move |data: i32| {
        println!("Got {data}")
    };

    let foo = 123;

    thread::spawn(move || {handle(foo)}).join();
}
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