|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +use super::{SpawnedTask, TaskFuture, TaskSpawner}; |
| 5 | +#[cfg(not(target_arch = "wasm32"))] |
| 6 | +use futures::{executor::LocalPool, task::SpawnExt}; |
| 7 | +#[cfg(not(target_arch = "wasm32"))] |
| 8 | +use std::{ |
| 9 | + future, |
| 10 | + future::Future, |
| 11 | + pin::Pin, |
| 12 | + sync::{Arc, Mutex}, |
| 13 | + task::Waker, |
| 14 | + task::{Context, Poll}, |
| 15 | + thread, |
| 16 | +}; |
| 17 | +#[cfg(not(target_arch = "wasm32"))] |
| 18 | +use tracing::debug; |
| 19 | + |
| 20 | +/// A future that completes when a thread join handle completes. |
| 21 | +#[cfg(not(target_arch = "wasm32"))] |
| 22 | +struct ThreadJoinFuture { |
| 23 | + join_state: Arc<Mutex<ThreadJoinState>>, |
| 24 | +} |
| 25 | + |
| 26 | +#[cfg(not(target_arch = "wasm32"))] |
| 27 | +#[derive(Default)] |
| 28 | +struct ThreadJoinState { |
| 29 | + join_handle: |
| 30 | + Option<thread::JoinHandle<std::result::Result<(), Box<dyn std::error::Error + Send>>>>, |
| 31 | + waker: Option<Waker>, |
| 32 | + thread_finished: bool, |
| 33 | +} |
| 34 | + |
| 35 | +#[cfg(not(target_arch = "wasm32"))] |
| 36 | +impl Future for ThreadJoinFuture { |
| 37 | + type Output = std::result::Result<(), Box<dyn std::error::Error + Send>>; |
| 38 | + |
| 39 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 40 | + let mut join_state = self.join_state.lock().map_err(|e| { |
| 41 | + debug!("Failed to lock join state: {}", e); |
| 42 | + Box::new(crate::Error::message( |
| 43 | + crate::error::ErrorKind::Other, |
| 44 | + format!("Thread panicked: {:?}", e), |
| 45 | + )) as Box<dyn std::error::Error + Send> |
| 46 | + })?; |
| 47 | + |
| 48 | + // Join handle is present, so we can check if the thread has finished |
| 49 | + // and take the handle if it has. |
| 50 | + // This is safe because we are holding the lock on the join state. |
| 51 | + // We can safely take the handle and join it without blocking. |
| 52 | + // This allows us to retrieve the terminal state of the thread. |
| 53 | + if join_state.thread_finished { |
| 54 | + // Thread is finished, so we can safely take the handle |
| 55 | + let Some(join_handle) = join_state.join_handle.take() else { |
| 56 | + // The join handle was already removed from the state, we know we're done. |
| 57 | + return Poll::Ready(Ok(())); |
| 58 | + }; |
| 59 | + |
| 60 | + // Since we know the thread is finished, we can safely take the handle |
| 61 | + // and join it. This allows us to retrieve the terminal state of the thread. |
| 62 | + // |
| 63 | + // Technically this might block (because the `thread_finished` flag |
| 64 | + // is set before the thread *actually* finishes), but it should be negligible. |
| 65 | + match join_handle.join() { |
| 66 | + Ok(_) => Poll::Ready(Ok(())), |
| 67 | + Err(e) => Poll::Ready(Err(Box::new(crate::Error::message( |
| 68 | + crate::error::ErrorKind::Other, |
| 69 | + format!("Thread panicked: {:?}", e), |
| 70 | + )) as Box<dyn std::error::Error + Send>)), |
| 71 | + } |
| 72 | + } else { |
| 73 | + // Thread is still running, so we need to register the waker |
| 74 | + // for when it completes. |
| 75 | + join_state.waker = Some(cx.waker().clone()); |
| 76 | + Poll::Pending |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +/// A [`TaskSpawner`] using [`std::thread::spawn`]. |
| 82 | +#[derive(Debug)] |
| 83 | +pub struct StdSpawner; |
| 84 | + |
| 85 | +impl TaskSpawner for StdSpawner { |
| 86 | + #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] |
| 87 | + fn spawn(&self, f: TaskFuture) -> SpawnedTask { |
| 88 | + #[cfg(target_arch = "wasm32")] |
| 89 | + { |
| 90 | + panic!("std::thread::spawn is not supported on wasm32") |
| 91 | + } |
| 92 | + #[cfg(not(target_arch = "wasm32"))] |
| 93 | + { |
| 94 | + let join_state = Arc::new(Mutex::new(ThreadJoinState::default())); |
| 95 | + { |
| 96 | + let Ok(mut js) = join_state.lock() else { |
| 97 | + return Box::pin(future::ready(Err(Box::new(crate::Error::message( |
| 98 | + crate::error::ErrorKind::Other, |
| 99 | + "Thread panicked.", |
| 100 | + )) |
| 101 | + as Box<dyn std::error::Error + Send>))); |
| 102 | + }; |
| 103 | + |
| 104 | + // Clone the join state so it can be moved into the thread |
| 105 | + // and used to notify the waker when the thread finishes. |
| 106 | + let join_state_clone = join_state.clone(); |
| 107 | + |
| 108 | + js.join_handle = Some(thread::spawn(move || { |
| 109 | + // Create a local executor |
| 110 | + let mut local_pool = LocalPool::new(); |
| 111 | + let spawner = local_pool.spawner(); |
| 112 | + |
| 113 | + // Spawn the future on the local executor |
| 114 | + let Ok(future_handle) = spawner.spawn_with_handle(f) else { |
| 115 | + return Err(Box::new(crate::Error::message( |
| 116 | + crate::error::ErrorKind::Other, |
| 117 | + "Failed to spawn future.", |
| 118 | + )) |
| 119 | + as Box<dyn std::error::Error + Send>); |
| 120 | + }; |
| 121 | + // Drive the executor until the future completes |
| 122 | + local_pool.run_until(future_handle); |
| 123 | + |
| 124 | + let Ok(mut join_state) = join_state_clone.lock() else { |
| 125 | + return Err(Box::new(crate::Error::message( |
| 126 | + crate::error::ErrorKind::Other, |
| 127 | + "Failed to lock join state", |
| 128 | + )) |
| 129 | + as Box<dyn std::error::Error + Send>); |
| 130 | + }; |
| 131 | + |
| 132 | + // The thread has finished, so we can take the waker |
| 133 | + // and notify it. |
| 134 | + join_state.thread_finished = true; |
| 135 | + if let Some(waker) = join_state.waker.take() { |
| 136 | + waker.wake(); |
| 137 | + } |
| 138 | + Ok(()) |
| 139 | + })); |
| 140 | + } |
| 141 | + // Create a future that will complete when the thread joins |
| 142 | + let join_future = ThreadJoinFuture { join_state }; |
| 143 | + Box::pin(join_future) |
| 144 | + } |
| 145 | + } |
| 146 | +} |
0 commit comments