forked from ProgrammingRust/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
spawn-blocking: Add example from Chapter 20, Asynchronous Programming.
- Loading branch information
Showing
4 changed files
with
129 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
/target/ | ||
Cargo.lock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
[package] | ||
name = "spawn-blocking" | ||
version = "0.1.0" | ||
authors = ["You <[email protected]>"] | ||
edition = "2018" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dev-dependencies] | ||
argonautica = "0.2" | ||
async-std = "1.7" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
#[cfg(test)] | ||
mod tests; | ||
|
||
use std::sync::{Arc, Mutex}; | ||
use std::task::Waker; | ||
|
||
pub struct SpawnBlocking<T>(Arc<Mutex<Shared<T>>>); | ||
|
||
struct Shared<T> { | ||
value: Option<T>, | ||
waker: Option<Waker>, | ||
} | ||
|
||
pub fn spawn_blocking<T, F>(closure: F) -> SpawnBlocking<T> | ||
where F: FnOnce() -> T, | ||
F: Send + 'static, | ||
T: Send + 'static, | ||
{ | ||
let inner = Arc::new(Mutex::new(Shared { | ||
value: None, | ||
waker: None, | ||
})); | ||
|
||
std::thread::spawn({ | ||
let inner = inner.clone(); | ||
move || { | ||
let value = closure(); | ||
|
||
let maybe_waker = { | ||
let mut guard = inner.lock().unwrap(); | ||
guard.value = Some(value); | ||
guard.waker.take() | ||
}; | ||
|
||
if let Some(waker) = maybe_waker { | ||
waker.wake(); | ||
} | ||
} | ||
}); | ||
|
||
SpawnBlocking(inner) | ||
} | ||
|
||
use std::future::Future; | ||
use std::pin::Pin; | ||
use std::task::{Context, Poll}; | ||
|
||
impl<T: Send> Future for SpawnBlocking<T> { | ||
type Output = T; | ||
|
||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> { | ||
let mut guard = self.0.lock().unwrap(); | ||
if let Some(value) = guard.value.take() { | ||
return Poll::Ready(value); | ||
} | ||
|
||
guard.waker = Some(cx.waker().clone()); | ||
Poll::Pending | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
use super::*; | ||
|
||
async fn verify_password(password: &str, hash: &str, key: &str) | ||
-> Result<bool, argonautica::Error> | ||
{ | ||
let password = password.to_string(); | ||
let hash = hash.to_string(); | ||
let key = key.to_string(); | ||
|
||
spawn_blocking(move || { | ||
argonautica::Verifier::default() | ||
.with_hash(hash) | ||
.with_password(password) | ||
.with_secret_key(key) | ||
.verify() | ||
}).await | ||
} | ||
|
||
static PASSWORD: &str = "P@ssw0rd"; | ||
static HASH: &str = "$argon2id$v=19$m=4096,t=192,p=4$\ | ||
o2y5PU86Vt+sr93N7YUGgC7AMpTKpTQCk4tNGUPZMY4$\ | ||
yzP/ukZRPIbZg6PvgnUUobUMbApfF9RH6NagL9L4Xr4\ | ||
"; | ||
static SECRET_KEY: &str = "secret key that you should really store in a .env file \ | ||
instead of in code, but this is just an example\ | ||
"; | ||
|
||
#[test] | ||
fn argonautica() { | ||
async_std::task::block_on(async { | ||
assert!(verify_password(PASSWORD, HASH, SECRET_KEY).await.unwrap()); | ||
}); | ||
} | ||
|
||
#[test] | ||
fn many_serial() { | ||
async_std::task::block_on(async { | ||
for i in 0..1000 { | ||
assert_eq!(spawn_blocking(move || i).await, i); | ||
} | ||
}); | ||
} | ||
|
||
#[test] | ||
fn many_parallel() { | ||
async_std::task::block_on(async { | ||
let futures: Vec<_> = (0..100) | ||
.map(|i| (i, spawn_blocking(move || i))) | ||
.collect(); | ||
|
||
for (i, f) in futures { | ||
assert_eq!(f.await, i); | ||
} | ||
}); | ||
} |