From 29e0420a3ae6a62125017f247847201e3de8493b Mon Sep 17 00:00:00 2001 From: Ivan Ukhov Date: Sun, 18 Aug 2024 09:08:30 +0200 Subject: [PATCH] Add an example of using async --- Cargo.toml | 1 + tests/connection.rs | 41 ++++++++++++++++++++++++++++++----------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 424c2d2d..274922c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,3 +44,4 @@ default-features = false [dev-dependencies] temporary = "0.6" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } diff --git a/tests/connection.rs b/tests/connection.rs index 0b5919fd..9e57726c 100644 --- a/tests/connection.rs +++ b/tests/connection.rs @@ -22,21 +22,40 @@ fn open_with_flags() { } } +#[tokio::test] +async fn open_thread_safe_async() { + use std::sync::Arc; + + use tokio::task::spawn_blocking as spawn; + + let connection = Arc::new(ok!(ok!( + spawn(|| Connection::open_thread_safe(":memory:")).await + ))); + + { + let connection = connection.clone(); + ok!(ok!(spawn(move || connection.execute("SELECT 1")).await)); + } + + { + let connection = connection.clone(); + ok!(ok!(spawn(move || connection.execute("SELECT 1")).await)); + } +} + #[test] -fn open_thread_safe() { +fn open_thread_safe_sync() { use std::sync::Arc; - use std::thread; + use std::thread::spawn; - let connection = ok!(Connection::open_thread_safe(":memory:")); - let connection = Arc::new(connection); + let connection = Arc::new(ok!(Connection::open_thread_safe(":memory:"))); let mut threads = Vec::new(); for _ in 0..5 { - let connection_ = connection.clone(); - let thread = thread::spawn(move || { - ok!(connection_.execute("SELECT 1")); - }); - threads.push(thread); + let connection = connection.clone(); + threads.push(spawn(move || { + ok!(connection.execute("SELECT 1")); + })); } for thread in threads { ok!(thread.join()); @@ -80,7 +99,7 @@ fn iterate() { #[test] fn set_busy_handler() { - use std::thread; + use std::thread::spawn; use temporary::Directory; let directory = ok!(Directory::new("sqlite")); @@ -90,7 +109,7 @@ fn set_busy_handler() { let guards = (0..10) .map(|_| { let path = path.to_path_buf(); - thread::spawn(move || { + spawn(move || { let mut connection = ok!(sqlite::open(&path)); ok!(connection.set_busy_handler(|_| true)); let query = "INSERT INTO users VALUES (?, ?, ?, ?, ?)";