Has type `std::sync::MutexGuard<’_, UpdateProgress>` which is not `Send`

73 阅读1分钟

在Rust中,需要需要多线程共享资源,一般需要使用Arc<Mutex>实现。这在rust本身多线程环境下没什么问题,但是当,需要在tokio等实现的async模块中使用会有有问题.

async fn some(){
let lock = Arc::new(Mutex::new<Vec<String>>);
 let list = lock.lock.unwarp();
}
    

这段代码在编译的时候会报Has type std::sync::MutexGuard<’_, UpdateProgress>which is notSend``异常。 特别是在使用axum这类框架的时候,会导致识别handler有问题。 会有以下异常: shell # Handler<_, _>` is not satisfied the following other types implement trait `Handler<T, S>`

其根本原因都是因为代码有问题,导致rust-analyer报错了。

可以通过cargo add axum --features="macros"

同时在handler上加上debug_handler来发现具体的问题。

#[debug_handler(state = Cache)]
async fn generate(Path(Param { spec, url }): Path<Param>,Extension(cache):Extension<Cache>) -> Result<impl IntoResponse, StatusCode> {
}

言归正传,如何解决future not implement Send呢,只需要使用tokio::sync::Mutex即可。