Skip to content

Commit f38923d

Browse files
committed
Add a small example on how to integrate threads
1 parent f8633ab commit f38923d

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

examples/integrate-thread.rs

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#![feature(async_await)]
2+
3+
use async_std::task;
4+
5+
use std::{thread,time};
6+
use futures::channel::oneshot;
7+
8+
struct AsyncHandle<T> {
9+
handle: thread::JoinHandle<T>,
10+
notifier: oneshot::Receiver<()>,
11+
}
12+
13+
impl<T> AsyncHandle<T> {
14+
fn thread(&self) -> &std::thread::Thread {
15+
self.handle.thread()
16+
}
17+
18+
async fn join(self) -> std::thread::Result<T> {
19+
// ignore results, the join handle will propagate panics
20+
let _ = self.notifier.await;
21+
self.handle.join()
22+
}
23+
}
24+
25+
26+
fn spawn<F,T>(f: F) -> AsyncHandle<T>
27+
where
28+
F: FnOnce() -> T,
29+
F: Send + 'static,
30+
T: Send + 'static,
31+
{
32+
let (sender, receiver) = oneshot::channel::<()>();
33+
34+
let thread_handle = thread::spawn(move || {
35+
let res = f();
36+
sender.send(()).unwrap();
37+
res
38+
});
39+
40+
AsyncHandle {
41+
handle: thread_handle,
42+
notifier: receiver
43+
}
44+
}
45+
46+
fn main() {
47+
let thread_handle = spawn(move || {
48+
thread::sleep(time::Duration::from_millis(1000));
49+
String::from("Finished")
50+
});
51+
52+
task::block_on(async move {
53+
println!("waiting for thread 1");
54+
let thread_result = thread_handle.join().await;
55+
match thread_result {
56+
Ok(s) => println!("Result: {}", s),
57+
Err(e) => println!("Error: {:?}", e),
58+
}
59+
});
60+
61+
let thread_handle = spawn(move || {
62+
panic!("aaah!");
63+
String::from("Finished!")
64+
});
65+
66+
task::block_on(async move {
67+
println!("waiting for thread 2");
68+
let thread_result = thread_handle.join().await;
69+
match thread_result {
70+
Ok(s) => println!("Result: {}", s),
71+
Err(e) => println!("Error: {:?}", e),
72+
}
73+
});
74+
}

0 commit comments

Comments
 (0)