Debian Codegraph @

src/pool.rs

raw symbols SCIP
1 //! Implementation of the thread pool itself.
2
3 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::{
4 fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/,
5 futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/::Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#,
6 opsrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/::{Rangerust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#, RangeInclusiverust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeInclusive#, RangeTorust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeTo#, RangeToInclusiverust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeToInclusive#},
7 syncrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/::{
8 atomicrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/::{AtomicUsizerust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/AtomicUsize#, Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#},
9 Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#,
10 Condvarrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/Condvar#,
11 Mutexrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/Mutex#,
12 },
13 threadrust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/,
14 timerust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/::{Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#, Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#},
15 };
16
17 use crossbeam_channelrust-analyzer cargo crossbeam-channel 0.5.16 crate/::{boundedrust-analyzer cargo crossbeam-channel 0.5.16 channel/bounded()., unboundedrust-analyzer cargo crossbeam-channel 0.5.16 channel/unbounded()., Receiverrust-analyzer cargo crossbeam-channel 0.5.16 channel/Receiver#, Senderrust-analyzer cargo crossbeam-channel 0.5.16 channel/Sender#};
18 use once_cellrust-analyzer cargo once_cell 1.21.4 crate/::syncrust-analyzer cargo once_cell 1.21.4 sync/::Lazyrust-analyzer cargo once_cell 1.21.4 sync/Lazy#;
19
20 use craterust-analyzer cargo threadfin 0.1.2 crate/::{
21 errorrust-analyzer cargo threadfin 0.1.2 error/::PoolFullErrorrust-analyzer cargo threadfin 0.1.2 error/PoolFullError#,
22 taskrust-analyzer cargo threadfin 0.1.2 task/::{Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#, Taskrust-analyzer cargo threadfin 0.1.2 task/Task#},
23 workerrust-analyzer cargo threadfin 0.1.2 worker/::{Listenerrust-analyzer cargo threadfin 0.1.2 worker/Listener#, Workerrust-analyzer cargo threadfin 0.1.2 worker/Worker#},
24 };
25
26 #[cfg(threadfin_has_atomic64)]
27 type AtomicCounterrust-analyzer cargo threadfin 0.1.2 pool/AtomicCounter# = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::syncrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/::atomicrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/::AtomicU64rust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/AtomicU64#;
28
29 #[cfg(not(threadfin_has_atomic64))]
30 type AtomicCounter = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::syncrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/::atomicrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/::AtomicU32rust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/AtomicU32#;
31
32 /// A value describing a size constraint for a thread pool.
33 ///
34 /// Any size constraint can be wrapped in [`PerCore`] to be made relative to the
35 /// number of available CPU cores on the current system.
36 ///
37 /// See [`Builder::size`] for details.
38 pub trait SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# {
39 /// Get the minimum number of threads to be in the thread pool.
40 fn minrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#min().(&self) -> usize;
41
42 /// Get the maximum number of threads to be in the thread pool.
43 fn maxrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#max().(&self) -> usize;
44 }
45
46 impl SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# for usize {
47 fn minrust-analyzer cargo threadfin 0.1.2 pool/impl#[usize][SizeConstraint]min().(&self) -> usize {
48 *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&T`][Deref]deref().self
49 }
50
51 fn maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[usize][SizeConstraint]max().(&self) -> usize {
52 *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&T`][Deref]deref().self
53 }
54 }
55
56 impl SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# for Rangerust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#<usize> {
57 fn minrust-analyzer cargo threadfin 0.1.2 pool/impl#[`Range<usize>`][SizeConstraint]min().(&self) -> usize {
58 self.startrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#start.
59 }
60
61 fn maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[`Range<usize>`][SizeConstraint]max().(&self) -> usize {
62 self.endrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#end.
63 }
64 }
65
66 impl SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# for RangeInclusiverust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeInclusive#<usize> {
67 fn minrust-analyzer cargo threadfin 0.1.2 pool/impl#[`RangeInclusive<usize>`][SizeConstraint]min().(&self) -> usize {
68 *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&T`][Deref]deref().self.startrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/impl#[`RangeInclusive<Idx>`]start().()
69 }
70
71 fn maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[`RangeInclusive<usize>`][SizeConstraint]max().(&self) -> usize {
72 *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&T`][Deref]deref().self.endrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/impl#[`RangeInclusive<Idx>`]end().()
73 }
74 }
75
76 impl SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# for RangeTorust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeTo#<usize> {
77 fn minrust-analyzer cargo threadfin 0.1.2 pool/impl#[`RangeTo<usize>`][SizeConstraint]min().(&self) -> usize {
78 0
79 }
80
81 fn maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[`RangeTo<usize>`][SizeConstraint]max().(&self) -> usize {
82 self.endrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeTo#end.
83 }
84 }
85
86 impl SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# for RangeToInclusiverust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeToInclusive#<usize> {
87 fn minrust-analyzer cargo threadfin 0.1.2 pool/impl#[`RangeToInclusive<usize>`][SizeConstraint]min().(&self) -> usize {
88 0
89 }
90
91 fn maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[`RangeToInclusive<usize>`][SizeConstraint]max().(&self) -> usize {
92 self.endrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeToInclusive#end.
93 }
94 }
95
96 /// Modifies a size constraint to be per available CPU core.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// # use threadfin::PerCore;
102 /// // one thread per core
103 /// let size = PerCore(1);
104 ///
105 /// // four threads per core
106 /// let size = PerCore(4);
107 ///
108 /// // at least 1 thread per core and at most 2 threads per core
109 /// let size = PerCore(1..2);
110 /// ```
111 pub struct PerCorerust-analyzer cargo threadfin 0.1.2 pool/PerCore#<T>(pub T);
112
113 static CORE_COUNTrust-analyzer cargo threadfin 0.1.2 pool/CORE_COUNT.: Lazyrust-analyzer cargo once_cell 1.21.4 sync/Lazy#<usize> = Lazyrust-analyzer cargo once_cell 1.21.4 sync/Lazy#::newrust-analyzer cargo once_cell 1.21.4 sync/impl#[`Lazy<T, F>`]new().(|| num_cpusrust-analyzer cargo num_cpus 1.17.0 crate/::getrust-analyzer cargo num_cpus 1.17.0 get().().maxrust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/Ord#max().(1));
114
115 impl<T> Fromrust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/From#<T> for PerCorerust-analyzer cargo threadfin 0.1.2 pool/PerCore#<T> {
116 fn fromrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][`From<T>`]from().(size: T) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][`From<T>`] {
117 Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][`From<T>`](size)
118 }
119 }
120
121 impl<T: SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#> SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint# for PerCorerust-analyzer cargo threadfin 0.1.2 pool/PerCore#<T> {
122 fn minrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][SizeConstraint]min().(&self) -> usize {
123 *rust-analyzer cargo once_cell 1.21.4 sync/impl#[`Lazy<T, F>`][Deref]deref().CORE_COUNTrust-analyzer cargo threadfin 0.1.2 pool/CORE_COUNT. rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Mul<Self>`]mul().*rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Mul<Self>`]mul(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Mul<Self>`]mul().self.0rust-analyzer cargo threadfin 0.1.2 pool/PerCore#0..minrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#min().()
124 }
125
126 fn maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][SizeConstraint]max().(&self) -> usize {
127 *rust-analyzer cargo once_cell 1.21.4 sync/impl#[`Lazy<T, F>`][Deref]deref().CORE_COUNTrust-analyzer cargo threadfin 0.1.2 pool/CORE_COUNT. rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Mul<Self>`]mul().*rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Mul<Self>`]mul(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Mul<Self>`]mul().self.0rust-analyzer cargo threadfin 0.1.2 pool/PerCore#0..maxrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#max().()
128 }
129 }
130
131 /// A builder for constructing a customized [`ThreadPool`].
132 ///
133 /// # Examples
134 ///
135 /// ```
136 /// let custom_pool = threadfin::builder()
137 /// .name("my-pool")
138 /// .size(2)
139 /// .build();
140 /// ```
141 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/macros/Debug:)]
142 pub struct Builderrust-analyzer cargo threadfin 0.1.2 pool/Builder# {
143 namerust-analyzer cargo threadfin 0.1.2 pool/Builder#name.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#>,
144 sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#size.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<(usize, usize)>,
145 stack_sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#stack_size.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<usize>,
146 queue_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#queue_limit.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<usize>,
147 worker_concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#worker_concurrency_limit.: usize,
148 keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Builder#keep_alive.: Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#,
149 }
150
151 impl Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default# for Builderrust-analyzer cargo threadfin 0.1.2 pool/Builder# {
152 fn defaultrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder][Default]default().() -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder][Default] {
153 Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder][Default] {
154 namerust-analyzer cargo threadfin 0.1.2 pool/Builder#name.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
155 sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#size.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
156 stack_sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#stack_size.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
157 queue_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#queue_limit.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
158 worker_concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#worker_concurrency_limit.: 16,
159 keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Builder#keep_alive.: Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#::from_secsrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/impl#[Duration]from_secs().(60),
160 }
161 }
162 }
163
164 impl Builderrust-analyzer cargo threadfin 0.1.2 pool/Builder# {
165 /// Set a custom thread name for threads spawned by this thread pool.
166 ///
167 /// # Panics
168 ///
169 /// Panics if the name contains null bytes (`\0`).
170 ///
171 /// # Examples
172 ///
173 /// ```
174 /// let pool = threadfin::builder().name("my-pool").build();
175 /// ```
176 pub fn namerust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]name().<T: Intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/Into#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#>>(mut self, name: T) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder] {
177 let name = name.intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/Into#into().();
178
179 if name.as_bytesrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String]as_bytes().().containsrust-analyzer cargo core https://github.com/rust-lang/rust/library/core slice/impl#[`[T]`]contains().(&0) {
180 panicrust-analyzer cargo std https://github.com/rust-lang/rust/library/std macros/panic!!("thread pool name must not contain null bytes");
181 }
182
183 self.namerust-analyzer cargo threadfin 0.1.2 pool/Builder#name. = Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(name);
184 self
185 }
186
187 /// Set the number of threads to be managed by this thread pool.
188 ///
189 /// If a `usize` is supplied, the pool will have a fixed number of threads.
190 /// If a range is supplied, the lower bound will be the core pool size while
191 /// the upper bound will be a maximum pool size the pool is allowed to burst
192 /// up to when the core threads are busy.
193 ///
194 /// Any size constraint can be wrapped in [`PerCore`] to be made relative to
195 /// the number of available CPU cores on the current system.
196 ///
197 /// If not set, a reasonable size will be selected based on the number of
198 /// CPU cores on the current system.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// // Create a thread pool with exactly 2 threads.
204 /// let pool = threadfin::builder().size(2).build();
205 /// ```
206 ///
207 /// ```
208 /// // Create a thread pool with no idle threads, but will spawn up to 4
209 /// // threads lazily when there's work to be done.
210 /// let pool = threadfin::builder().size(0..4).build();
211 ///
212 /// // Or equivalently:
213 /// let pool = threadfin::builder().size(..4).build();
214 /// ```
215 ///
216 /// ```
217 /// use threadfin::PerCore;
218 ///
219 /// // Create a thread pool with two threads per core.
220 /// let pool = threadfin::builder().size(PerCore(2)).build();
221 /// ```
222 ///
223 /// # Panics
224 ///
225 /// Panics if an invalid range is supplied with a lower bound larger than
226 /// the upper bound, or if the upper bound is 0.
227 pub fn sizerust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]size().<S: SizeConstraintrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#>(mut self, size: S) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder] {
228 let (min, max) = (size.minrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#min().(), size.maxrust-analyzer cargo threadfin 0.1.2 pool/SizeConstraint#max().());
229
230 if min rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt().>rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt().max {
231 panicrust-analyzer cargo std https://github.com/rust-lang/rust/library/std macros/panic!!("thread pool minimum size cannot be larger than maximum size");
232 }
233
234 if max rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq().0 {
235 panicrust-analyzer cargo std https://github.com/rust-lang/rust/library/std macros/panic!!("thread pool maximum size must be non-zero");
236 }
237
238 self.sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#size. = Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#((min, max));
239 self
240 }
241
242 /// Set the size of the stack (in bytes) for threads in this thread pool.
243 ///
244 /// The actual stack size may be greater than this value if the platform
245 /// enforces a larger minimum stack size.
246 ///
247 /// The stack size if not specified will be the default size for new Rust
248 /// threads, currently 2 MiB. This can also be overridden by setting the
249 /// `RUST_MIN_STACK` environment variable if not specified in code.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// // Worker threads will have a stack size of at least 32 KiB.
255 /// let pool = threadfin::builder().stack_size(32 * 1024).build();
256 /// ```
257 pub fn stack_sizerust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]stack_size().(mut self, size: usize) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder] {
258 self.stack_sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#stack_size. = Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(size);
259 self
260 }
261
262 /// Set a maximum number of pending tasks allowed to be submitted before
263 /// blocking.
264 ///
265 /// If set to zero, queueing will be disabled and attempting to execute a
266 /// new task will block until an idle worker thread can immediately begin
267 /// executing the task or a new worker thread can be created to execute the
268 /// task.
269 ///
270 /// If not set, no limit is enforced.
271 pub fn queue_limitrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]queue_limit().(mut self, limit: usize) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder] {
272 self.queue_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#queue_limit. = Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(limit);
273 self
274 }
275
276 /// Set a duration for how long to keep idle worker threads alive.
277 ///
278 /// If the pool has more than the minimum configured number of threads and
279 /// threads remain idle for more than this duration, they will be terminated
280 /// until the minimum thread count is reached.
281 pub fn keep_aliverust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]keep_alive().(mut self, duration: Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder] {
282 self.keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Builder#keep_alive. = duration;
283 self
284 }
285
286 /// Set a limit on the number of concurrent tasks that can be run by a
287 /// single worker thread.
288 ///
289 /// When executing asynchronous tasks, if the underlying future being
290 /// executed yields, that worker thread can begin working on new tasks
291 /// concurrently while waiting on the prior task to resume. This allows for
292 /// a primitive M:N scheduling model that supports running significantly
293 /// more futures concurrently than the number of threads in the thread pool.
294 ///
295 /// To prevent a worker thread from over-committing to too many tasks at
296 /// once (which could result in extra latency if a task wakes but its
297 /// assigned worker is too busy with other tasks) worker threads limit
298 /// themselves to a maximum number of concurrent tasks. This method allows
299 /// you to customize that limit.
300 ///
301 /// The default limit if not specified is 16.
302 pub fn worker_concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]worker_concurrency_limit().(mut self, limit: usize) -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder] {
303 self.worker_concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#worker_concurrency_limit. = limit;
304 self
305 }
306
307 /// Create a thread pool according to the configuration set with this
308 /// builder.
309 pub fn buildrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]build().(self) -> ThreadPoolrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool# {
310 let size = self.sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#size..unwrap_or_elserust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap_or_else().(|| {
311 let size = PerCorerust-analyzer cargo threadfin 0.1.2 pool/PerCore#(1..rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#2);
312
313 (size.minrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][SizeConstraint]min().(), size.maxrust-analyzer cargo threadfin 0.1.2 pool/impl#[`PerCore<T>`][SizeConstraint]max().())
314 });
315
316 let shared = Sharedrust-analyzer cargo threadfin 0.1.2 pool/Shared# {
317 min_threadsrust-analyzer cargo threadfin 0.1.2 pool/Shared#min_threads.: size.0,
318 max_threadsrust-analyzer cargo threadfin 0.1.2 pool/Shared#max_threads.: size.1,
319 thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count.: Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default#::defaultrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`Mutex<T>`][Default]default().(),
320 running_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#running_tasks_count.: Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default#::defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicUsize][Default]default().(),
321 completed_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#completed_tasks_count.: Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default#::defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicU64][Default]default().(),
322 panicked_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#panicked_tasks_count.: Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default#::defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicU64][Default]default().(),
323 keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Shared#keep_alive.: self.keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Builder#keep_alive.,
324 shutdown_cvarrust-analyzer cargo threadfin 0.1.2 pool/Shared#shutdown_cvar.: Condvarrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/Condvar#::newrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/impl#[Condvar]new().(),
325 };
326
327 let pool = ThreadPoolrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool# {
328 thread_namerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#thread_name.: self.namerust-analyzer cargo threadfin 0.1.2 pool/Builder#name.,
329 stack_sizerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#stack_size.: self.stack_sizerust-analyzer cargo threadfin 0.1.2 pool/Builder#stack_size.,
330 concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#concurrency_limit.: self.worker_concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#worker_concurrency_limit.,
331 queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue.: self.queue_limitrust-analyzer cargo threadfin 0.1.2 pool/Builder#queue_limit..maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]map().(boundedrust-analyzer cargo crossbeam-channel 0.5.16 channel/bounded().).unwrap_or_elserust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap_or_else().(unboundedrust-analyzer cargo crossbeam-channel 0.5.16 channel/unbounded().),
332 immediate_queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#immediate_queue.: boundedrust-analyzer cargo crossbeam-channel 0.5.16 channel/bounded().(0),
333 sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared.: Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/impl#[`Arc<T>`]new().(shared),
334 };
335
336 for _ in 0..rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/Range#size.0 {
337 let result = pool.spawn_threadrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]spawn_thread().(Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#);
338 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(result.is_okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_ok().());
339 }
340
341 pool
342 }
343 }
344
345 /// A thread pool for running multiple tasks on a configurable group of threads.
346 ///
347 /// Thread pools can improve performance when executing a large number of
348 /// concurrent tasks since the expensive overhead of spawning threads is
349 /// minimized as threads are re-used for multiple tasks. Thread pools are also
350 /// useful for controlling and limiting parallelism.
351 ///
352 /// Dropping the thread pool will prevent any further tasks from being scheduled
353 /// on the pool and detaches all threads in the pool. If you want to block until
354 /// all pending tasks have completed and the pool is entirely shut down, then
355 /// use one of the available [`join`](ThreadPool::join) methods.
356 ///
357 /// # Pool size
358 ///
359 /// Every thread pool has a minimum and maximum number of worker threads that it
360 /// will spawn for executing tasks. This range is known as the _pool size_, and
361 /// affects pool behavior in the following ways:
362 ///
363 /// - **Minimum size**: A guaranteed number of threads that will always be
364 /// created and maintained by the thread pool. Threads will be eagerly created
365 /// to meet this minimum size when the pool is created, and at least this many
366 /// threads will be kept running in the pool until the pool is shut down.
367 /// - **Maximum size**: A limit on the number of additional threads to spawn to
368 /// execute more work.
369 ///
370 /// # Queueing
371 ///
372 /// If a new or existing worker thread is unable to immediately start processing
373 /// a submitted task, that task will be placed in a queue for worker threads to
374 /// take from when they complete their current tasks. Queueing is only used when
375 /// it is not possible to directly handoff a task to an existing thread and
376 /// spawning a new thread would exceed the pool's configured maximum size.
377 ///
378 /// By default, thread pools are configured to use an _unbounded_ queue which
379 /// can hold an unlimited number of pending tasks. This is a sensible default,
380 /// but is not desirable in all use-cases and can be changed with
381 /// [`Builder::queue_limit`].
382 ///
383 /// # Monitoring
384 ///
385 /// Each pool instance provides methods for gathering various statistics on the
386 /// pool's usage, such as number of current number of threads, tasks completed
387 /// over time, and queued tasks. While these methods provide the most up-to-date
388 /// numbers upon invocation, they should not be used for controlling program
389 /// behavior since they can become immediately outdated due to the live nature
390 /// of the pool.
391 pub struct ThreadPoolrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool# {
392 thread_namerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#thread_name.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#>,
393 stack_sizerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#stack_size.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<usize>,
394 concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#concurrency_limit.: usize,
395 queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue.: (Senderrust-analyzer cargo crossbeam-channel 0.5.16 channel/Sender#<Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#>, Receiverrust-analyzer cargo crossbeam-channel 0.5.16 channel/Receiver#<Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#>),
396 immediate_queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#immediate_queue.: (Senderrust-analyzer cargo crossbeam-channel 0.5.16 channel/Sender#<Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#>, Receiverrust-analyzer cargo crossbeam-channel 0.5.16 channel/Receiver#<Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#>),
397 sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared.: Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#<Sharedrust-analyzer cargo threadfin 0.1.2 pool/Shared#>,
398 }
399
400 impl Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default# for ThreadPoolrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool# {
401 fn defaultrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool][Default]default().() -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool][Default] {
402 Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool][Default]::newrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]new().()
403 }
404 }
405
406 impl ThreadPoolrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool# {
407 /// Create a new thread pool with the default configuration.
408 ///
409 /// If you'd like to customize the thread pool's behavior then use
410 /// [`ThreadPool::builder`].
411 #[inline]
412 pub fn newrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]new().() -> Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool] {
413 Selfrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]::builderrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]builder().().buildrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder]build().()
414 }
415
416 /// Get a builder for creating a customized thread pool.
417 #[inline]
418 pub fn builderrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]builder().() -> Builderrust-analyzer cargo threadfin 0.1.2 pool/Builder# {
419 Builderrust-analyzer cargo threadfin 0.1.2 pool/Builder#::defaultrust-analyzer cargo threadfin 0.1.2 pool/impl#[Builder][Default]default().()
420 }
421
422 /// Get the number of threads currently running in the thread pool.
423 pub fn threadsrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]threads().(&self) -> usize {
424 *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`MutexGuard<'_, T>`][Deref]deref().self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count..lockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`Mutex<T>`]lock().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().()
425 }
426
427 /// Get the number of tasks queued for execution, but not yet started.
428 ///
429 /// This number will always be less than or equal to the configured
430 /// [`queue_limit`](Builder::queue_limit), if any.
431 ///
432 /// Note that the number returned may become immediately outdated after
433 /// invocation.
434 ///
435 /// # Examples
436 ///
437 /// ```
438 /// use std::{thread::sleep, time::Duration};
439 ///
440 /// // Create a pool with just one thread.
441 /// let pool = threadfin::builder().size(1).build();
442 ///
443 /// // Nothing is queued yet.
444 /// assert_eq!(pool.queued_tasks(), 0);
445 ///
446 /// // Start a slow task.
447 /// let task = pool.execute(|| {
448 /// sleep(Duration::from_millis(100));
449 /// });
450 ///
451 /// // Wait a little for the task to start.
452 /// sleep(Duration::from_millis(10));
453 /// assert_eq!(pool.queued_tasks(), 0);
454 ///
455 /// // Enqueue some more tasks.
456 /// let count = 4;
457 /// for _ in 0..count {
458 /// pool.execute(|| {
459 /// // work to do
460 /// });
461 /// }
462 ///
463 /// // The tasks should still be in the queue because the slow task is
464 /// // running on the only thread.
465 /// assert_eq!(pool.queued_tasks(), count);
466 /// # pool.join();
467 /// ```
468 #[inline]
469 pub fn queued_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]queued_tasks().(&self) -> usize {
470 self.queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue..0.lenrust-analyzer cargo crossbeam-channel 0.5.16 channel/impl#[`Sender<T>`]len().()
471 }
472
473 /// Get the number of tasks currently running.
474 ///
475 /// Note that the number returned may become immediately outdated after
476 /// invocation.
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use std::{thread::sleep, time::Duration};
482 ///
483 /// let pool = threadfin::ThreadPool::new();
484 ///
485 /// // Nothing is running yet.
486 /// assert_eq!(pool.running_tasks(), 0);
487 ///
488 /// // Start a task.
489 /// let task = pool.execute(|| {
490 /// sleep(Duration::from_millis(100));
491 /// });
492 ///
493 /// // Wait a little for the task to start.
494 /// sleep(Duration::from_millis(10));
495 /// assert_eq!(pool.running_tasks(), 1);
496 ///
497 /// // Wait for the task to complete.
498 /// task.join();
499 /// assert_eq!(pool.running_tasks(), 0);
500 /// ```
501 #[inline]
502 pub fn running_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]running_tasks().(&self) -> usize {
503 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..running_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#running_tasks_count..loadrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicUsize]load().(Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::Relaxedrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#Relaxed#)
504 }
505
506 /// Get the number of tasks completed (successfully or otherwise) by this
507 /// pool since it was created.
508 ///
509 /// Note that the number returned may become immediately outdated after
510 /// invocation.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// let pool = threadfin::ThreadPool::new();
516 /// assert_eq!(pool.completed_tasks(), 0);
517 ///
518 /// pool.execute(|| 2 + 2).join();
519 /// assert_eq!(pool.completed_tasks(), 1);
520 ///
521 /// pool.execute(|| 2 + 2).join();
522 /// assert_eq!(pool.completed_tasks(), 2);
523 /// ```
524 #[inline]
525 #[allow(clippy::useless_conversion)]
526 pub fn completed_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]completed_tasks().(&self) -> u64 {
527 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..completed_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#completed_tasks_count..loadrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicU64]load().(Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::Relaxedrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#Relaxed#).intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().()
528 }
529
530 /// Get the number of tasks that have panicked since the pool was created.
531 ///
532 /// Note that the number returned may become immediately outdated after
533 /// invocation.
534 ///
535 /// # Examples
536 ///
537 /// ```
538 /// use std::{thread::sleep, time::Duration};
539 ///
540 /// let pool = threadfin::ThreadPool::new();
541 /// assert_eq!(pool.panicked_tasks(), 0);
542 ///
543 /// let task = pool.execute(|| {
544 /// panic!("this task panics");
545 /// });
546 ///
547 /// while !task.is_done() {
548 /// sleep(Duration::from_millis(100));
549 /// }
550 ///
551 /// assert_eq!(pool.panicked_tasks(), 1);
552 /// ```
553 #[inline]
554 #[allow(clippy::useless_conversion)]
555 pub fn panicked_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]panicked_tasks().(&self) -> u64 {
556 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..panicked_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#panicked_tasks_count..loadrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicU64]load().(Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::SeqCstrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#SeqCst#).intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().()
557 }
558
559 /// Submit a closure to be executed by the thread pool.
560 ///
561 /// If all worker threads are busy, but there are less threads than the
562 /// configured maximum, an additional thread will be created and added to
563 /// the pool to execute this task.
564 ///
565 /// If all worker threads are busy and the pool has reached the configured
566 /// maximum number of threads, the task will be enqueued. If the queue is
567 /// configured with a limit, this call will block until space becomes
568 /// available in the queue.
569 ///
570 /// # Examples
571 ///
572 /// ```
573 /// let pool = threadfin::ThreadPool::new();
574 /// let task = pool.execute(|| {
575 /// 2 + 2 // some expensive computation
576 /// });
577 ///
578 /// // do something in the meantime
579 ///
580 /// // now wait for the result
581 /// let sum = task.join();
582 /// assert_eq!(sum, 4);
583 /// ```
584 pub fn executerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]execute().<T, F>(&self, closure: F) -> Taskrust-analyzer cargo threadfin 0.1.2 task/Task#<T>
585 where
586 T: Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
587 F: FnOncerust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/function/FnOnce#() -> T + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
588 {
589 let (task, coroutine) = Taskrust-analyzer cargo threadfin 0.1.2 task/Task#::from_closurerust-analyzer cargo threadfin 0.1.2 task/impl#[`Task<T>`]from_closure().(closure);
590
591 self.execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]execute_coroutine().(coroutine);
592
593 task
594 }
595
596 /// Submit a future to be executed by the thread pool.
597 ///
598 /// If all worker threads are busy, but there are less threads than the
599 /// configured maximum, an additional thread will be created and added to
600 /// the pool to execute this task.
601 ///
602 /// If all worker threads are busy and the pool has reached the configured
603 /// maximum number of threads, the task will be enqueued. If the queue is
604 /// configured with a limit, this call will block until space becomes
605 /// available in the queue.
606 ///
607 /// # Thread locality
608 ///
609 /// While the given future must implement [`Send`] to be moved into a thread
610 /// in the pool to be processed, once the future is assigned a thread it
611 /// will stay assigned to that single thread until completion. This improves
612 /// cache locality even across `.await` points in the future.
613 ///
614 /// ```
615 /// let pool = threadfin::ThreadPool::new();
616 /// let task = pool.execute_future(async {
617 /// 2 + 2 // some asynchronous code
618 /// });
619 ///
620 /// // do something in the meantime
621 ///
622 /// // now wait for the result
623 /// let sum = task.join();
624 /// assert_eq!(sum, 4);
625 /// ```
626 pub fn execute_futurerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]execute_future().<T, F>(&self, future: F) -> Taskrust-analyzer cargo threadfin 0.1.2 task/Task#<T>
627 where
628 T: Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
629 F: Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#<Outputrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#Output# = T> + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
630 {
631 let (task, coroutine) = Taskrust-analyzer cargo threadfin 0.1.2 task/Task#::from_futurerust-analyzer cargo threadfin 0.1.2 task/impl#[`Task<T>`]from_future().(future);
632
633 self.execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]execute_coroutine().(coroutine);
634
635 task
636 }
637
638 /// Attempts to execute a closure on the thread pool without blocking.
639 ///
640 /// If the pool is at its max thread count and the task queue is full, the
641 /// task is rejected and an error is returned. The original closure can be
642 /// extracted from the error.
643 ///
644 /// # Examples
645 ///
646 /// One use for this method is implementing backpressure by executing a
647 /// closure on the current thread if a pool is currently full.
648 ///
649 /// ```
650 /// let pool = threadfin::ThreadPool::new();
651 ///
652 /// // Try to run a closure in the thread pool.
653 /// let result = pool.try_execute(|| 2 + 2)
654 /// // If successfully submitted, block until the task completes.
655 /// .map(|task| task.join())
656 /// // If the pool was full, invoke the closure here and now.
657 /// .unwrap_or_else(|error| error.into_inner()());
658 ///
659 /// assert_eq!(result, 4);
660 /// ```
661 pub fn try_executerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]try_execute().<T, F>(&self, closure: F) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Taskrust-analyzer cargo threadfin 0.1.2 task/Task#<T>, PoolFullErrorrust-analyzer cargo threadfin 0.1.2 error/PoolFullError#<F>>
662 where
663 T: Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
664 F: FnOncerust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/function/FnOnce#() -> T + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
665 {
666 let (task, coroutine) = Taskrust-analyzer cargo threadfin 0.1.2 task/Task#::from_closurerust-analyzer cargo threadfin 0.1.2 task/impl#[`Task<T>`]from_closure().(closure);
667
668 self.try_execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]try_execute_coroutine().(coroutine)
669 .maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]map().(|_| task)
670 .map_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]map_err().(|coroutine| PoolFullErrorrust-analyzer cargo threadfin 0.1.2 error/PoolFullError#(coroutine.into_inner_closurerust-analyzer cargo threadfin 0.1.2 task/impl#[Coroutine]into_inner_closure().()))
671 }
672
673 /// Attempts to execute a future on the thread pool without blocking.
674 ///
675 /// If the pool is at its max thread count and the task queue is full, the
676 /// task is rejected and an error is returned. The original future can be
677 /// extracted from the error.
678 pub fn try_execute_futurerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]try_execute_future().<T, F>(&self, future: F) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Taskrust-analyzer cargo threadfin 0.1.2 task/Task#<T>, PoolFullErrorrust-analyzer cargo threadfin 0.1.2 error/PoolFullError#<F>>
679 where
680 T: Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
681 F: Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#<Outputrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#Output# = T> + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + 'static,
682 {
683 let (task, coroutine) = Taskrust-analyzer cargo threadfin 0.1.2 task/Task#::from_futurerust-analyzer cargo threadfin 0.1.2 task/impl#[`Task<T>`]from_future().(future);
684
685 self.try_execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]try_execute_coroutine().(coroutine)
686 .maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]map().(|_| task)
687 .map_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]map_err().(|coroutine| PoolFullErrorrust-analyzer cargo threadfin 0.1.2 error/PoolFullError#(coroutine.into_inner_futurerust-analyzer cargo threadfin 0.1.2 task/impl#[Coroutine]into_inner_future().()))
688 }
689
690 fn execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]execute_coroutine().(&self, coroutine: Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#) {
691 if let Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(coroutine) = self.try_execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]try_execute_coroutine().(coroutine) {
692 // Cannot fail because we hold a reference to both the channel
693 // sender and receiver and it cannot be closed here.
694 self.queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue..0.sendrust-analyzer cargo crossbeam-channel 0.5.16 channel/impl#[`Sender<T>`]send().(coroutine).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
695 }
696 }
697
698 fn try_execute_coroutinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]try_execute_coroutine().(&self, coroutine: Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#> {
699 // First, try to pass the coroutine to an idle worker currently polling
700 // for work. This is the most favorable scenario for a task to begin
701 // processing.
702 if let Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) = self.immediate_queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#immediate_queue..0.try_sendrust-analyzer cargo crossbeam-channel 0.5.16 channel/impl#[`Sender<T>`]try_send().(coroutine) {
703 // Error means no workers are currently polling the queue.
704 debug_assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/debug_assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().e.is_disconnectedrust-analyzer cargo crossbeam-channel 0.5.16 err/impl#[`TrySendError<T>`]is_disconnected().());
705
706 // If possible, spawn an additional thread to handle the task.
707 if let Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) = self.spawn_threadrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]spawn_thread().(Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(e.into_innerrust-analyzer cargo crossbeam-channel 0.5.16 err/impl#[`TrySendError<T>`]into_inner().())) {
708 // Finally as a last resort, enqueue the task into the queue,
709 // but only if it isn't full.
710 if let Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) = self.queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue..0.try_sendrust-analyzer cargo crossbeam-channel 0.5.16 channel/impl#[`Sender<T>`]try_send().(e.unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap().()) {
711 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e.into_innerrust-analyzer cargo crossbeam-channel 0.5.16 err/impl#[`TrySendError<T>`]into_inner().());
712 }
713 }
714 }
715
716 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(())
717 }
718
719 /// Shut down this thread pool and block until all existing tasks have
720 /// completed and threads have stopped.
721 pub fn joinrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join().(self) {
722 self.join_internalrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join_internal().(Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#);
723 }
724
725 /// Shut down this thread pool and block until all existing tasks have
726 /// completed and threads have stopped, or until the given timeout passes.
727 ///
728 /// Returns `true` if the thread pool shut down fully before the timeout.
729 pub fn join_timeoutrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join_timeout().(self, timeout: Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#) -> bool {
730 self.join_deadlinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join_deadline().(Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#::nowrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant]now().() rust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant][`Add<Duration>`]add().+rust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant][`Add<Duration>`]add(). rust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant][`Add<Duration>`]add().timeout)
731 }
732
733 /// Shut down this thread pool and block until all existing tasks have
734 /// completed and threads have stopped, or the given deadline passes.
735 ///
736 /// Returns `true` if the thread pool shut down fully before the deadline.
737 pub fn join_deadlinerust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join_deadline().(self, deadline: Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#) -> bool {
738 self.join_internalrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join_internal().(Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(deadline))
739 }
740
741 fn join_internalrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]join_internal().(self, deadline: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#>) -> bool {
742 // Closing this channel will interrupt any idle workers and signal to
743 // all workers that the pool is shutting down.
744 droprust-analyzer cargo core https://github.com/rust-lang/rust/library/core mem/drop().(self.queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue..0);
745
746 let mut thread_count = self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count..lockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`Mutex<T>`]lock().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
747
748 while *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`MutexGuard<'_, T>`][Deref]deref().thread_count rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt().>rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt().0 {
749 // If a deadline is set, figure out how much time is remaining and
750 // wait for that amount.
751 if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(deadline) = deadline {
752 if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(timeout) = deadline.checked_duration_sincerust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant]checked_duration_since().(Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#::nowrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant]now().()) {
753 thread_count = self
754 .sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared.
755 .shutdown_cvarrust-analyzer cargo threadfin 0.1.2 pool/Shared#shutdown_cvar.
756 .wait_timeoutrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/impl#[Condvar]wait_timeout().(thread_count, timeout)
757 .unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().()
758 .0;
759 } else {
760 return false;
761 }
762 }
763 // If a deadline is not set, wait forever.
764 else {
765 thread_count = self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..shutdown_cvarrust-analyzer cargo threadfin 0.1.2 pool/Shared#shutdown_cvar..waitrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/impl#[Condvar]wait().(thread_count).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
766 }
767 }
768
769 true
770 }
771
772 /// Spawn an additional thread into the thread pool, if possible.
773 ///
774 /// If an initial thunk is given, it will be the first thunk the thread
775 /// executes once ready for work.
776 fn spawn_threadrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]spawn_thread().(&self, initial_task: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#>) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Coroutinerust-analyzer cargo threadfin 0.1.2 task/Coroutine#>> {
777 struct WorkerListenerrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener# {
778 sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared.: Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#<Sharedrust-analyzer cargo threadfin 0.1.2 pool/Shared#>,
779 }
780
781 impl Listenerrust-analyzer cargo threadfin 0.1.2 worker/Listener# for WorkerListenerrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener# {
782 fn on_task_startedrust-analyzer cargo threadfin 0.1.2 pool/impl#[WorkerListener][Listener]on_task_started().(&mut self) {
783 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared.
784 .running_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#running_tasks_count.
785 .fetch_addrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicUsize]fetch_add().(1, Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::Relaxedrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#Relaxed#);
786 }
787
788 fn on_task_completedrust-analyzer cargo threadfin 0.1.2 pool/impl#[WorkerListener][Listener]on_task_completed().(&mut self, panicked: bool) {
789 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared.
790 .running_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#running_tasks_count.
791 .fetch_subrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicUsize]fetch_sub().(1, Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::Relaxedrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#Relaxed#);
792 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared.
793 .completed_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#completed_tasks_count.
794 .fetch_addrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicU64]fetch_add().(1, Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::Relaxedrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#Relaxed#);
795
796 if panicked {
797 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared.
798 .panicked_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#panicked_tasks_count.
799 .fetch_addrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/impl#[AtomicU64]fetch_add().(1, Orderingrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#::SeqCstrust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/Ordering#SeqCst#);
800 }
801 }
802
803 fn on_idlerust-analyzer cargo threadfin 0.1.2 pool/impl#[WorkerListener][Listener]on_idle().(&mut self) -> bool {
804 // Check if the worker should shut down by seeing if we are over
805 // the minimum worker count.
806 *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`MutexGuard<'_, T>`][Deref]deref().self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared..thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count..lockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`Mutex<T>`]lock().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().() rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt().>rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]gt().self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared..min_threadsrust-analyzer cargo threadfin 0.1.2 pool/Shared#min_threads.
807 }
808 }
809
810 impl Droprust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/drop/Drop# for WorkerListenerrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener# {
811 fn droprust-analyzer cargo threadfin 0.1.2 pool/impl#[WorkerListener][Drop]drop().(&mut self) {
812 if let Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(mut count) = self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared..thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count..lockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`Mutex<T>`]lock().() {
813 *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`MutexGuard<'_, T>`][DerefMut]deref_mut().count = count.saturating_subrust-analyzer cargo core https://github.com/rust-lang/rust/library/core num/impl#[usize]saturating_sub().(1);
814 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared..shutdown_cvarrust-analyzer cargo threadfin 0.1.2 pool/Shared#shutdown_cvar..notify_allrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/impl#[Condvar]notify_all().();
815 }
816 }
817 }
818
819 // Lock the thread count to prevent race conditions when determining
820 // whether new threads can be created.
821 let mut thread_count = self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count..lockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`Mutex<T>`]lock().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
822
823 // We've reached the configured limit for threads, do nothing.
824 if *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`MutexGuard<'_, T>`][Deref]deref().thread_count rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]ge().>=rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]ge(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialOrd<Self>`]ge().self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..max_threadsrust-analyzer cargo threadfin 0.1.2 pool/Shared#max_threads. {
825 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(initial_task);
826 }
827
828 // Configure the thread based on the thread pool configuration.
829 let mut builder = threadrust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/::Builderrust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/builder/Builder#::newrust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/builder/impl#[Builder]new().();
830
831 if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(name) = self.thread_namerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#thread_name..as_refrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]as_ref().() {
832 builder = builder.namerust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/builder/impl#[Builder]name().(name.clonerust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String][Clone]clone().());
833 }
834
835 if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(size) = self.stack_sizerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#stack_size. {
836 builder = builder.stack_sizerust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/builder/impl#[Builder]stack_size().(size);
837 }
838
839 *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/impl#[`MutexGuard<'_, T>`][DerefMut]deref_mut().thread_count rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`AddAssign<Self>`]add_assign().+=rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`AddAssign<Self>`]add_assign(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`AddAssign<Self>`]add_assign().1;
840
841 let worker = Workerrust-analyzer cargo threadfin 0.1.2 worker/Worker#::newrust-analyzer cargo threadfin 0.1.2 worker/impl#[`Worker<L>`]new().(
842 initial_task,
843 self.queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#queue..1.clonerust-analyzer cargo crossbeam-channel 0.5.16 channel/impl#[`Receiver<T>`][Clone]clone().(),
844 self.immediate_queuerust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#immediate_queue..1.clonerust-analyzer cargo crossbeam-channel 0.5.16 channel/impl#[`Receiver<T>`][Clone]clone().(),
845 self.concurrency_limitrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#concurrency_limit.,
846 self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Shared#keep_alive.,
847 WorkerListenerrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener# {
848 sharedrust-analyzer cargo threadfin 0.1.2 pool/WorkerListener#shared.: self.sharedrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool#shared..clonerust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/impl#[`Arc<T, A>`][Clone]clone().(),
849 },
850 );
851
852 // We can now safely unlock the thread count since the worker struct
853 // will decrement the count again if it is dropped.
854 droprust-analyzer cargo core https://github.com/rust-lang/rust/library/core mem/drop().(thread_count);
855
856 builder.spawnrust-analyzer cargo std https://github.com/rust-lang/rust/library/std thread/builder/impl#[Builder]spawn().(move || worker.runrust-analyzer cargo threadfin 0.1.2 worker/impl#[`Worker<L>`]run().()).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
857
858 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(())
859 }
860 }
861
862 impl fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/::Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/Debug# for ThreadPoolrust-analyzer cargo threadfin 0.1.2 pool/ThreadPool# {
863 fn fmtrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool][Debug]fmt().(&self, f: &mut fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/::Formatterrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/Formatter#<'_>) -> fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/::Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/Result# {
864 f.debug_structrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/impl#[`Formatter<'a>`]debug_struct().("ThreadPool")
865 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("queued_tasks", &self.queued_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]queued_tasks().())
866 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("running_tasks", &self.running_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]running_tasks().())
867 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("completed_tasks", &self.completed_tasksrust-analyzer cargo threadfin 0.1.2 pool/impl#[ThreadPool]completed_tasks().())
868 .finishrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]finish().()
869 }
870 }
871
872 /// Thread pool state shared by the owner and the worker threads.
873 struct Sharedrust-analyzer cargo threadfin 0.1.2 pool/Shared# {
874 min_threadsrust-analyzer cargo threadfin 0.1.2 pool/Shared#min_threads.: usize,
875 max_threadsrust-analyzer cargo threadfin 0.1.2 pool/Shared#max_threads.: usize,
876 thread_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#thread_count.: Mutexrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/mutex/Mutex#<usize>,
877 running_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#running_tasks_count.: AtomicUsizerust-analyzer cargo core https://github.com/rust-lang/rust/library/core sync/atomic/AtomicUsize#,
878 completed_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#completed_tasks_count.: AtomicCounterrust-analyzer cargo threadfin 0.1.2 pool/AtomicCounter#,
879 panicked_tasks_countrust-analyzer cargo threadfin 0.1.2 pool/Shared#panicked_tasks_count.: AtomicCounterrust-analyzer cargo threadfin 0.1.2 pool/AtomicCounter#,
880 keep_aliverust-analyzer cargo threadfin 0.1.2 pool/Shared#keep_alive.: Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#,
881 shutdown_cvarrust-analyzer cargo threadfin 0.1.2 pool/Shared#shutdown_cvar.: Condvarrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/condvar/Condvar#,
882 }