Hi! So I'm learning how to deal with async tasks and try to understand how to make them work. So far most of the issues have been solved by wrapping variables in an Arc<Mutex> for spawning them in a separate thread. The problem comes when I try to call a method from self
containing a generic.
So for example (this is a minimal example to reproduce my case, it's not the actual code I'm working in), let's say I have this struct (I'm currently using tokio, but I assume the issue is not specific to the library):
struct MyStruct<B> {
other: B
}
impl<B: std::fmt::Display> MyStruct<B> {
async fn print_b(&self) {
println!("{}", self.other);
}
async fn call_async(&self) {
tokio::spawn(async move {
self.print_b().await;
});
}
}
I'm obviously getting the error:
future cannot be sent between threads safely
future created by async block is not `Send`
The error makes sense, as we don't have any way to know that B
implements Send
, and actually it doesn't have to. But I'm having a lot of trouble figuring out how should I solve this. So is there a way to solve this in a more or less elegant way?