Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 1 | //! A function that runs a future to completion on a dedicated thread. |
| 2 | |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 3 | use std::future::Future; |
| 4 | use std::sync::Arc; |
| 5 | use std::thread; |
| 6 | |
| 7 | use crossbeam::channel; |
| 8 | use futures::executor; |
| 9 | |
| 10 | /// Spawns a future on a new dedicated thread. |
| 11 | /// |
| 12 | /// The returned handle can be used to await the output of the future. |
| 13 | fn spawn_on_thread<F, R>(future: F) -> async_task::JoinHandle<R, ()> |
| 14 | where |
| 15 | F: Future<Output = R> + Send + 'static, |
| 16 | R: Send + 'static, |
| 17 | { |
| 18 | // Create a channel that holds the task when it is scheduled for running. |
| 19 | let (sender, receiver) = channel::unbounded(); |
| 20 | let sender = Arc::new(sender); |
| 21 | let s = Arc::downgrade(&sender); |
| 22 | |
| 23 | // Wrap the future into one that disconnects the channel on completion. |
| 24 | let future = async move { |
| 25 | // When the inner future completes, the sender gets dropped and disconnects the channel. |
| 26 | let _sender = sender; |
| 27 | future.await |
| 28 | }; |
| 29 | |
| 30 | // Create a task that is scheduled by sending itself into the channel. |
| 31 | let schedule = move |t| s.upgrade().unwrap().send(t).unwrap(); |
| 32 | let (task, handle) = async_task::spawn(future, schedule, ()); |
| 33 | |
| 34 | // Schedule the task by sending it into the channel. |
| 35 | task.schedule(); |
| 36 | |
| 37 | // Spawn a thread running the task to completion. |
| 38 | thread::spawn(move || { |
| 39 | // Keep taking the task from the channel and running it until completion. |
| 40 | for task in receiver { |
| 41 | task.run(); |
| 42 | } |
| 43 | }); |
| 44 | |
| 45 | handle |
| 46 | } |
| 47 | |
| 48 | fn main() { |
| 49 | // Spawn a future on a dedicated thread. |
| 50 | executor::block_on(spawn_on_thread(async { |
| 51 | println!("Hello, world!"); |
| 52 | })); |
| 53 | } |