I am in the process of learning Rust.
This code runs fine with cargo run
. However
When I run cargo clippy
, I get the following warning and I am looking for a solution. await_holding_lock I understand the content, but I just can't seem to resolve the warning. I am sorry, but I am not sure how to improve this issue. I am sorry, but could you please tell me how to improve it?
- Code
se anyhow::Result;
use tokio_postgres::{Client, NoTls};
use once_cell::sync::Lazy;
use std::sync::Mutex;
use crate::params::ConnectParams;
pub static CONNECT_PARAMS: Lazy<Mutex<ConnectParams>> =
Lazy::new(||{
let params = ConnectParams::new(
"localhost".to_owned(), 5432, "rust_sample".to_owned(),
"postgres".to_owned(), "admin".to_owned()
);
Mutex::new(params)
});
pub struct AsyncSimpleClient;
impl AsyncSimpleClient {
pub async fn connect() -> Result<Client> {
let params = CONNECT_PARAMS.lock().unwrap(); // params lock here.
let config = params.connect_string().clone();
let (client, connection) = tokio_postgres::connect(config.as_str(), NoTls).await?;
let handle = tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("Connection error: {}", e);
}
});
Ok(client)
} // params drop here.
}
- Warning
warning: this `MutexGuard` is held across an `await` point
--> practice_collection/postgres/src/tokio_connect.rs:23:13
|
23 | let params = CONNECT_PARAMS.lock().unwrap();
| ^^^^^^
|
= help: consider using an async-aware `Mutex` type or ensuring the `MutexGuard` is dropped before calling await
note: these are all the `await` points this lock is held through
--> practice_collection/postgres/src/tokio_connect.rs:23:9
|
23 | / let params = CONNECT_PARAMS.lock().unwrap();
24 | | let config = params.connect_string().clone();
25 | | let (client, connection) = tokio_postgres::connect(config.as_str(), NoTls).await?;
26 | | let handle = tokio::spawn(async move {
... |
32 | | Ok(client)
33 | | }
| |_____^
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#await_holding_lock
= note: `#[warn(clippy::await_holding_lock)]` on by default