Using lock().unwrap().as_mut() instead of interact() to avoid using static lifetime for a &str #269
-
For a function Following the example in the deadpool / diesel directory, with interact.rs: use deadpool_diesel::sqlite::{Manager, Pool, Runtime};
use diesel::{prelude::*, select, sql_types::Text};
async fn print_async(pool: &Pool, message: &'static str) {
let conn = pool.get().await.unwrap();
let result = conn
.interact(move |conn| {
let query = select(message.clone().into_sql::<Text>());
query.get_result::<String>(conn)
})
.await;
println!("{:?}", result.unwrap().unwrap());
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let manager = Manager::new(":memory:", Runtime::Tokio1);
let pool = Pool::builder(manager).max_size(8).build().unwrap();
let future1 = print_async(&pool, "Hello World!");
let future2 = print_async(&pool, "Good bye!");
tokio::join!(future1, future2);
Ok(())
} And without the additional thread, lock.rs: use deadpool_diesel::sqlite::{Manager, Pool, Runtime};
use diesel::{prelude::*, select, sql_types::Text};
async fn print_async(pool: &Pool, message: &str) {
let conn = pool.get().await.unwrap();
let query = select(message.into_sql::<Text>());
let result = query
.get_result::<String>(conn.lock().unwrap().as_mut())
.unwrap();
println!("{:?}", result);
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let manager = Manager::new(":memory:", Runtime::Tokio1);
let pool = Pool::builder(manager).max_size(8).build().unwrap();
let future1 = print_async(&pool, "Hello World!");
let future2 = print_async(&pool, "Good bye!");
tokio::join!(future1, future2);
Ok(())
} I have two questions:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Without the worker you (can) end up blocking you entire async reactor. You might not run into any problems as some runtimes try to detect this kind of usage and spawn a new thread under the hood in order to prevent this kind of situation. This is however by no means "good practice" and you are better of spawning a thread yourself. That's essentially what You're of course free to call btw. spawning threads is (usually) very cheap and runtimes make that even cheaper by implementing a thread pool under the hood. So repeated calls to |
Beta Was this translation helpful? Give feedback.
You need to use a
Box<str>
, not aBox<&str>
. If that gives you any headaches just use aString
. The performance difference is negligible.