Hello, I'm newbie in Rust and trying to do some multithreading stuff.
Long story short, here's what I'm trying to accomplish :
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use std::thread;
fn main() {
let (tx, rx) = channel::<i32>();
thread::spawn(move || stuff(tx));
for val in rx {
println!("{}", val);
}
}
async fn stuff(tx: Sender<i32>) {
tx.send(42);
tx.send(69);
tx.send(123);
}
But stuff() seems to never get executed. What am I missing ?
How do I execute a future async fn with thread::spawn ?
Don't mark your function as async
In your case, you just want to execute a "normal" (synchronous) function on another thread.
By declaring stuff to be async you make it return a Future, which is the encapsulation of an asynchronous operation. You would need to give that to an executor to actually execute it. When compiling your code, Rust should also issue a warning that the Future created by stuff(tx) is unused. Edit: it does not.
It is a simplified version of what I'm trying to do, I made it async because the stuff function originally contained a call to async function reqwest::get("https://somestuff.com") and compiler required me for it to be encapsulated in async function.
Generally you don't want to be using block_on from futures. Use a real executor if you must use async code. In your case, you don't want async at all, so just use the blocking module.
Notice how you can await on an async function
additionally you can spawn a task to run simultaneously. See how task1 and task2 print together instead of one after another.