1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
45use super::common::{Executor, ExecutorTime, MAIN_TASK_ID};
6use super::scope::ScopeHandle;
7use fuchsia_sync::{Condvar, Mutex};
89use futures::FutureExt;
10use std::future::Future;
11use std::sync::atomic::Ordering;
12use std::sync::Arc;
13use std::time::Duration;
14use std::{fmt, thread};
1516/// A multi-threaded port-based executor for Fuchsia. Requires that tasks scheduled on it
17/// implement `Send` so they can be load balanced between worker threads.
18///
19/// Having a `SendExecutor` in scope allows the creation and polling of zircon objects, such as
20/// [`fuchsia_async::Channel`].
21///
22/// # Panics
23///
24/// `SendExecutor` will panic on drop if any zircon objects attached to it are still alive. In other
25/// words, zircon objects backed by a `SendExecutor` must be dropped before it.
26pub struct SendExecutor {
27/// The inner executor state.
28inner: Arc<Executor>,
29// LINT.IfChange
30/// The root scope.
31root_scope: ScopeHandle,
32// LINT.ThenChange(//src/developer/debug/zxdb/console/commands/verb_async_backtrace.cc)
33/// Worker thread handles
34threads: Vec<thread::JoinHandle<()>>,
35 worker_init: Option<Arc<dyn Fn() + Send + Sync + 'static>>,
36}
3738impl fmt::Debug for SendExecutor {
39fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 f.debug_struct("SendExecutor").field("port", &self.inner.port).finish()
41 }
42}
4344impl SendExecutor {
45/// Create a new multi-threaded executor.
46#[allow(deprecated)]
47pub fn new(num_threads: u8) -> Self {
48Self::new_inner(num_threads, None)
49 }
5051/// Set a new worker initialization callback. Will be invoked once at the start of each worker
52 /// thread.
53pub fn set_worker_init(&mut self, worker_init: impl Fn() + Send + Sync + 'static) {
54self.worker_init = Some(Arc::new(worker_init) as Arc<dyn Fn() + Send + Sync + 'static>);
55 }
5657/// Apply the worker initialization callback to an owned executor, returning the executor.
58 ///
59 /// The initialization callback will be invoked once at the start of each worker thread.
60pub fn with_worker_init(mut self, worker_init: fn()) -> Self {
61self.set_worker_init(worker_init);
62self
63}
6465fn new_inner(
66 num_threads: u8,
67 worker_init: Option<Arc<dyn Fn() + Send + Sync + 'static>>,
68 ) -> Self {
69let inner =
70 Arc::new(Executor::new(ExecutorTime::RealTime, /* is_local */ false, num_threads));
71let root_scope = ScopeHandle::root(inner.clone());
72 Executor::set_local(root_scope.clone());
73Self { inner, root_scope, threads: Vec::default(), worker_init }
74 }
7576/// Get a reference to the Fuchsia `zx::Port` being used to listen for events.
77pub fn port(&self) -> &zx::Port {
78&self.inner.port
79 }
8081/// Run `future` to completion, using this thread and `num_threads` workers in a pool to
82 /// poll active tasks.
83// The debugger looks for this function on the stack, so if its (fully-qualified) name changes,
84 // the debugger needs to be updated.
85 // LINT.IfChange
86pub fn run<F>(&mut self, future: F) -> F::Output
87// LINT.ThenChange(//src/developer/debug/zxdb/console/commands/verb_async_backtrace.cc)
88where
89F: Future + Send + 'static,
90 F::Output: Send + 'static,
91 {
92assert!(self.inner.is_real_time(), "Error: called `run` on an executor using fake time");
9394let pair = Arc::new((Mutex::new(None), Condvar::new()));
95let pair2 = pair.clone();
9697// Spawn a future which will set the result upon completion.
98let task = self.root_scope.new_task(
99Some(MAIN_TASK_ID),
100 future.map(move |fut_result| {
101let (lock, cvar) = &*pair2;
102let mut result = lock.lock();
103*result = Some(fut_result);
104 cvar.notify_one();
105 }),
106 );
107 task.detach();
108assert!(self.root_scope.insert_task(task, false));
109110// Start worker threads, handing off timers from the current thread.
111self.inner.done.store(false, Ordering::SeqCst);
112self.create_worker_threads();
113114// Wait until the signal the future has completed.
115let (lock, cvar) = &*pair;
116let mut result = lock.lock();
117if result.is_none() {
118let mut last_polled = 0;
119let mut last_tasks_ready = false;
120loop {
121// This timeout is chosen to be quite high since it impacts all processes that have
122 // multi-threaded async executors, and it exists to workaround arguably misbehaving
123 // users (see the comment below).
124cvar.wait_for(&mut result, Duration::from_millis(250));
125if result.is_some() {
126break;
127 }
128let polled = self.inner.polled.load(Ordering::Relaxed);
129let tasks_ready = !self.inner.ready_tasks.is_empty();
130if polled == last_polled && last_tasks_ready && tasks_ready {
131// If this log message is printed, it most likely means that a task has blocked
132 // making a reentrant synchronous call that doesn't involve a port message being
133 // processed by this same executor. This can arise even if you would expect
134 // there to normally be other port messages involved. One example (that has
135 // actually happened): spawn a task to service a fuchsia.io connection, then try
136 // and synchronously connect to that service. If the task hasn't had a chance to
137 // run, then the async channel might not be registered with the executor, and so
138 // sending messages to the channel doesn't trigger a port message. Typically,
139 // the way to solve these issues is to run the service in a different executor
140 // (which could be the same or a different process).
141eprintln!("Tasks might be stalled!");
142self.inner.wake_one_thread();
143 }
144 last_polled = polled;
145 last_tasks_ready = tasks_ready;
146 }
147 }
148149// Spin down worker threads
150self.join_all();
151152// Unwrap is fine because of the check to `is_none` above.
153result.take().unwrap()
154 }
155156#[doc(hidden)]
157/// Returns the root scope of the executor.
158pub fn root_scope(&self) -> &ScopeHandle {
159&self.root_scope
160 }
161162/// Add `self.num_threads` worker threads to the executor's thread pool.
163 /// `timers`: timers from the "main" thread which would otherwise be lost.
164fn create_worker_threads(&mut self) {
165for _ in 0..self.inner.num_threads {
166let inner = self.inner.clone();
167let root_scope = self.root_scope.clone();
168let worker_init = self.worker_init.clone();
169let thread = thread::Builder::new()
170 .name("executor_worker".to_string())
171 .spawn(move || {
172 Executor::set_local(root_scope);
173if let Some(init) = worker_init.as_ref() {
174 init();
175 }
176 inner.worker_lifecycle::</* UNTIL_STALLED: */ false>();
177 })
178 .expect("must be able to spawn threads");
179self.threads.push(thread);
180 }
181 }
182183fn join_all(&mut self) {
184self.inner.mark_done();
185186// Join the worker threads
187for thread in self.threads.drain(..) {
188 thread.join().expect("Couldn't join worker thread.");
189 }
190 }
191}
192193impl Drop for SendExecutor {
194fn drop(&mut self) {
195self.join_all();
196self.inner.on_parent_drop(&self.root_scope);
197 }
198}
199200// TODO(https://fxbug.dev/42156503) test SendExecutor with unit tests
201202#[cfg(test)]
203mod tests {
204use super::SendExecutor;
205use crate::{Task, Timer};
206207use futures::channel::oneshot;
208use std::sync::atomic::{AtomicU64, Ordering};
209use std::sync::{Arc, Condvar, Mutex};
210211#[test]
212fn test_stalled_triggers_wake_up() {
213 SendExecutor::new(2).run(async {
214// The timer will only fire on one thread, so use one so we can get to a point where
215 // only one thread is running.
216Timer::new(zx::MonotonicDuration::from_millis(10)).await;
217218let (tx, rx) = oneshot::channel();
219let pair = Arc::new((Mutex::new(false), Condvar::new()));
220let pair2 = pair.clone();
221222let _task = Task::spawn(async move {
223// Send a notification to the other task.
224tx.send(()).unwrap();
225// Now block the thread waiting for the result.
226let (lock, cvar) = &*pair;
227let mut done = lock.lock().unwrap();
228while !*done {
229 done = cvar.wait(done).unwrap();
230 }
231 });
232233 rx.await.unwrap();
234let (lock, cvar) = &*pair2;
235*lock.lock().unwrap() = true;
236 cvar.notify_one();
237 });
238 }
239240#[test]
241fn worker_init_called_once_per_worker() {
242static NUM_INIT_CALLS: AtomicU64 = AtomicU64::new(0);
243fn initialize_test_worker() {
244 NUM_INIT_CALLS.fetch_add(1, Ordering::SeqCst);
245 }
246247let mut exec = SendExecutor::new(2).with_worker_init(initialize_test_worker);
248 exec.run(async {});
249assert_eq!(NUM_INIT_CALLS.load(Ordering::SeqCst), 2);
250 exec.run(async {});
251assert_eq!(NUM_INIT_CALLS.load(Ordering::SeqCst), 4);
252 }
253}