'a
in spawn_blocking
#6562
-
In many cases, the task is not async fn hash(content: &str) -> anyhow::Result<String> {
let content = content.to_string();
tokio::task::spawn_blocking(move || util::hash::sha256::digest(&content)).await?
} Is there any way to avoid clone the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
You might use |
Beta Was this translation helpful? Give feedback.
-
@Darksonn Oh that's bad. Is there any plan to support this situation? |
Beta Was this translation helpful? Give feedback.
-
Why unsafe code like this cannot be used? use tokio::task::{JoinError, spawn_blocking};
pub async fn spawn_blocking_local<R: Send + 'static, F: FnOnce() -> R + Send>(local: F) -> Result<R, JoinError> {
let raw = Box::into_raw(Box::new(local)) as usize;
spawn_blocking(move || {
let func = *unsafe { Box::from_raw(raw as *mut F) };
func()
}).await
} I tested and no problem. #[tokio::main]
async fn main() -> Result<()> {
let mutex = Mutex::new(123);
let borrow = mutex.lock().await;
let local = move || { println!("{}", &borrow) };
spawn_blocking_local(local).await?;
Ok(())
} @Darksonn I'm sorry to bother you again, but I really want to know the reason. |
Beta Was this translation helpful? Give feedback.
Because of cancellation. Consider this example, where a string is used after it is freed.