blob: 24431d2a4c0d64b4a847ff5ce8e226c95749362e [file] [log] [blame]
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This module implements the handling of async tasks.
16//! The worker thread has a high priority and a low priority queue. Adding a job to either
17//! will cause one thread to be spawned if none exists. As a compromise between performance
18//! and resource consumption, the thread will linger for about 30 seconds after it has
19//! processed all tasks before it terminates.
20//! Note that low priority tasks are processed only when the high priority queue is empty.
21
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -080022use std::{any::Any, any::TypeId, time::Duration};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080023use std::{
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -080024 collections::{HashMap, VecDeque},
Janis Danisevskis93927dd2020-12-23 12:23:08 -080025 sync::Arc,
26 sync::{Condvar, Mutex, MutexGuard},
27 thread,
28};
29
30#[derive(Debug, PartialEq, Eq)]
31enum State {
32 Exiting,
33 Running,
34}
35
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -080036/// The Shelf allows async tasks to store state across invocations.
37/// Note: Store elves at your own peril ;-).
38#[derive(Debug, Default)]
39pub struct Shelf(HashMap<TypeId, Box<dyn Any + Send>>);
40
41impl Shelf {
42 /// Get a reference to the shelved data of type T. Returns Some if the data exists.
43 pub fn get_downcast_ref<T: Any + Send>(&self) -> Option<&T> {
44 self.0.get(&TypeId::of::<T>()).and_then(|v| v.downcast_ref::<T>())
45 }
46
47 /// Get a mutable reference to the shelved data of type T. If a T was inserted using put,
48 /// get_mut, or get_or_put_with.
49 pub fn get_downcast_mut<T: Any + Send>(&mut self) -> Option<&mut T> {
50 self.0.get_mut(&TypeId::of::<T>()).and_then(|v| v.downcast_mut::<T>())
51 }
52
53 /// Remove the entry of the given type and returns the stored data if it existed.
54 pub fn remove_downcast_ref<T: Any + Send>(&mut self) -> Option<T> {
55 self.0.remove(&TypeId::of::<T>()).and_then(|v| v.downcast::<T>().ok().map(|b| *b))
56 }
57
58 /// Puts data `v` on the shelf. If there already was an entry of type T it is returned.
59 pub fn put<T: Any + Send>(&mut self, v: T) -> Option<T> {
60 self.0
61 .insert(TypeId::of::<T>(), Box::new(v) as Box<dyn Any + Send>)
62 .and_then(|v| v.downcast::<T>().ok().map(|b| *b))
63 }
64
65 /// Gets a mutable reference to the entry of the given type and default creates it if necessary.
66 /// The type must implement Default.
67 pub fn get_mut<T: Any + Send + Default>(&mut self) -> &mut T {
68 self.0
69 .entry(TypeId::of::<T>())
70 .or_insert_with(|| Box::new(T::default()) as Box<dyn Any + Send>)
71 .downcast_mut::<T>()
72 .unwrap()
73 }
74}
75
Janis Danisevskis93927dd2020-12-23 12:23:08 -080076struct AsyncTaskState {
77 state: State,
78 thread: Option<thread::JoinHandle<()>>,
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -080079 hi_prio_req: VecDeque<Box<dyn FnOnce(&mut Shelf) + Send>>,
80 lo_prio_req: VecDeque<Box<dyn FnOnce(&mut Shelf) + Send>>,
81 /// The store allows tasks to store state across invocations. It is passed to each invocation
82 /// of each task. Tasks need to cooperate on the ids they use for storing state.
83 shelf: Option<Shelf>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -080084}
85
86/// AsyncTask spawns one worker thread on demand to process jobs inserted into
87/// a low and a high priority work queue.
88pub struct AsyncTask {
89 state: Arc<(Condvar, Mutex<AsyncTaskState>)>,
90}
91
92impl Default for AsyncTask {
93 fn default() -> Self {
94 Self {
95 state: Arc::new((
96 Condvar::new(),
97 Mutex::new(AsyncTaskState {
98 state: State::Exiting,
99 thread: None,
100 hi_prio_req: VecDeque::new(),
101 lo_prio_req: VecDeque::new(),
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800102 shelf: None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800103 }),
104 )),
105 }
106 }
107}
108
109impl AsyncTask {
110 /// Adds a job to the high priority queue. High priority jobs are completed before
111 /// low priority jobs and can also overtake low priority jobs. But they cannot
112 /// preempt them.
113 pub fn queue_hi<F>(&self, f: F)
114 where
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800115 F: for<'r> FnOnce(&'r mut Shelf) + Send + 'static,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800116 {
117 self.queue(f, true)
118 }
119
120 /// Adds a job to the low priority queue. Low priority jobs are completed after
121 /// high priority. And they are not executed as long as high priority jobs are
122 /// present. Jobs always run to completion and are never preempted by high
123 /// priority jobs.
124 pub fn queue_lo<F>(&self, f: F)
125 where
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800126 F: FnOnce(&mut Shelf) + Send + 'static,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800127 {
128 self.queue(f, false)
129 }
130
131 fn queue<F>(&self, f: F, hi_prio: bool)
132 where
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800133 F: for<'r> FnOnce(&'r mut Shelf) + Send + 'static,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800134 {
135 let (ref condvar, ref state) = *self.state;
136 let mut state = state.lock().unwrap();
137 if hi_prio {
138 state.hi_prio_req.push_back(Box::new(f));
139 } else {
140 state.lo_prio_req.push_back(Box::new(f));
141 }
142
143 if state.state != State::Running {
144 self.spawn_thread(&mut state);
145 }
146 drop(state);
147 condvar.notify_all();
148 }
149
150 fn spawn_thread(&self, state: &mut MutexGuard<AsyncTaskState>) {
151 if let Some(t) = state.thread.take() {
152 t.join().expect("AsyncTask panicked.");
153 }
154
155 let cloned_state = self.state.clone();
156
157 state.thread = Some(thread::spawn(move || {
158 let (ref condvar, ref state) = *cloned_state;
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800159 // When the worker starts, it takes the shelf and puts it on the stack.
160 let mut shelf = state.lock().unwrap().shelf.take().unwrap_or_default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800161 loop {
162 if let Some(f) = {
163 let (mut state, timeout) = condvar
164 .wait_timeout_while(
165 state.lock().unwrap(),
166 Duration::from_secs(30),
167 |state| state.hi_prio_req.is_empty() && state.lo_prio_req.is_empty(),
168 )
169 .unwrap();
170 match (
171 state.hi_prio_req.pop_front(),
172 state.lo_prio_req.is_empty(),
173 timeout.timed_out(),
174 ) {
175 (Some(f), _, _) => Some(f),
176 (None, false, _) => state.lo_prio_req.pop_front(),
177 (None, true, true) => {
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800178 // When the worker exits it puts the shelf back into the shared
179 // state for the next worker to use. So state is preserved not
180 // only across invocations but also across worker thread shut down.
181 state.shelf = Some(shelf);
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800182 state.state = State::Exiting;
183 break;
184 }
185 (None, true, false) => None,
186 }
187 } {
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800188 f(&mut shelf)
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800189 }
190 }
191 }));
192 state.state = State::Running;
193 }
194}