summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDongHun Kwak <dh0128.kwak@samsung.com>2023-04-14 16:03:32 +0900
committerDongHun Kwak <dh0128.kwak@samsung.com>2023-04-14 16:03:32 +0900
commitbcec7ba2a9769f10561b5c133adcdc188a02d970 (patch)
treec913d36e0cbd57e6529a95952b03612b7e0a9fe9
downloadrust-easy-parallel-bcec7ba2a9769f10561b5c133adcdc188a02d970.tar.gz
rust-easy-parallel-bcec7ba2a9769f10561b5c133adcdc188a02d970.tar.bz2
rust-easy-parallel-bcec7ba2a9769f10561b5c133adcdc188a02d970.zip
Import easy-parallel 3.3.0upstream/3.3.0upstream
-rw-r--r--.cargo_vcs_info.json6
-rw-r--r--CHANGELOG.md35
-rw-r--r--Cargo.lock7
-rw-r--r--Cargo.toml30
-rw-r--r--Cargo.toml.orig16
-rw-r--r--LICENSE-APACHE201
-rw-r--r--LICENSE-MIT23
-rw-r--r--README.md83
-rw-r--r--examples/par_sum.rs23
-rw-r--r--src/lib.rs337
-rw-r--r--tests/smoke.rs38
11 files changed, 799 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..534f153
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "f17bf332776897ca7ee30e7824fb909a6de983ab"
+ },
+ "path_in_vcs": ""
+} \ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..b902187
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,35 @@
+# Version 3.3.0
+
+- Add `Parallel::collect()` and `Parallel::finish_in()` to allow for generic containers. (#9)
+
+# Version 3.2.0
+
+- Remove `T: Default` bound from `Default` impl.
+
+# Version 3.1.0
+
+- Add `Parallel::finish()`.
+
+# Version 3.0.0
+
+- Collect results in the same order closures were added.
+
+# Version 2.2.0
+
+- Remove `PhantomData` making `'a` invariant.
+
+# Version 2.1.0
+
+- Run one of the closures on the main thread.
+
+# Version 2.0.0
+
+- `Parallel::run()` now collects results.
+
+# Version 1.0.1
+
+- Remove unused `mut`.
+
+# Version 1.0.0
+
+- Initial version
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..593b166
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "easy-parallel"
+version = "3.3.0"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..a812203
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,30 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2018"
+rust-version = "1.35"
+name = "easy-parallel"
+version = "3.3.0"
+authors = ["Stjepan Glavina <stjepang@gmail.com>"]
+exclude = ["/.*"]
+description = "Run closures in parallel"
+homepage = "https://github.com/smol-rs/easy-parallel"
+readme = "README.md"
+keywords = [
+ "scope",
+ "thread",
+ "scoped",
+ "spawn",
+]
+categories = ["concurrency"]
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/smol-rs/easy-parallel"
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..940a114
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,16 @@
+[package]
+name = "easy-parallel"
+# When publishing a new version:
+# - Update CHANGELOG.md
+# - Create "v3.x.y" git tag
+version = "3.3.0"
+authors = ["Stjepan Glavina <stjepang@gmail.com>"]
+edition = "2018"
+rust-version = "1.35"
+description = "Run closures in parallel"
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/smol-rs/easy-parallel"
+homepage = "https://github.com/smol-rs/easy-parallel"
+keywords = ["scope", "thread", "scoped", "spawn"]
+categories = ["concurrency"]
+exclude = ["/.*"]
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..31aa793
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..aff5b86
--- /dev/null
+++ b/README.md
@@ -0,0 +1,83 @@
+# easy-parallel
+
+[![Build](https://github.com/smol-rs/easy-parallel/workflows/Build%20and%20test/badge.svg)](
+https://github.com/smol-rs/easy-parallel/actions)
+[![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](
+https://github.com/smol-rs/easy-parallel)
+[![Cargo](https://img.shields.io/crates/v/easy-parallel.svg)](
+https://crates.io/crates/easy-parallel)
+[![Documentation](https://docs.rs/easy-parallel/badge.svg)](
+https://docs.rs/easy-parallel)
+
+Run closures in parallel.
+
+This is a simple primitive for spawning threads in bulk and waiting for them to complete.
+Threads are allowed to borrow local variables from the main thread.
+
+# Examples
+
+Run two threads that increment a number:
+
+```rust
+use easy_parallel::Parallel;
+use std::sync::Mutex;
+
+let mut m = Mutex::new(0);
+
+Parallel::new()
+ .add(|| *m.lock().unwrap() += 1)
+ .add(|| *m.lock().unwrap() += 1)
+ .run();
+
+assert_eq!(*m.get_mut().unwrap(), 2);
+```
+
+Square each number of a vector on a different thread:
+
+```rust
+use easy_parallel::Parallel;
+
+let v = vec![10, 20, 30];
+
+let squares = Parallel::new()
+ .each(0..v.len(), |i| v[i] * v[i])
+ .run();
+
+assert_eq!(squares, [100, 400, 900]);
+```
+
+Compute the sum of numbers in an array:
+
+```rust
+use easy_parallel::Parallel;
+
+fn par_sum(v: &[i32]) -> i32 {
+ const THRESHOLD: usize = 2;
+
+ if v.len() <= THRESHOLD {
+ v.iter().copied().sum()
+ } else {
+ let half = (v.len() + 1) / 2;
+ let sums = Parallel::new().each(v.chunks(half), par_sum).run();
+ sums.into_iter().sum()
+ }
+}
+
+let v = [1, 25, -4, 10, 8];
+assert_eq!(par_sum(&v), 40);
+```
+
+## License
+
+Licensed under either of
+
+ * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
+ * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
+
+at your option.
+
+#### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
+dual licensed as above, without any additional terms or conditions.
diff --git a/examples/par_sum.rs b/examples/par_sum.rs
new file mode 100644
index 0000000..d662734
--- /dev/null
+++ b/examples/par_sum.rs
@@ -0,0 +1,23 @@
+use easy_parallel::Parallel;
+
+fn par_sum(v: &[i32]) -> i32 {
+ const THRESHOLD: usize = 100;
+
+ if v.len() <= THRESHOLD {
+ v.iter().copied().sum()
+ } else {
+ let half = (v.len() + 1) / 2;
+ let sums = Parallel::new().each(v.chunks(half), par_sum).run();
+ sums.into_iter().sum()
+ }
+}
+
+fn main() {
+ let mut v = Vec::new();
+ for i in 0..10_000 {
+ v.push(i);
+ }
+
+ let sum = dbg!(par_sum(&v));
+ assert_eq!(sum, v.into_iter().sum());
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..6bef1c5
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,337 @@
+//! Run closures in parallel.
+//!
+//! This is a simple primitive for spawning threads in bulk and waiting for them to complete.
+//! Threads are allowed to borrow local variables from the main thread.
+//!
+//! # Examples
+//!
+//! Run two threads that increment a number:
+//!
+//! ```
+//! use easy_parallel::Parallel;
+//! use std::sync::Mutex;
+//!
+//! let mut m = Mutex::new(0);
+//!
+//! Parallel::new()
+//! .add(|| *m.lock().unwrap() += 1)
+//! .add(|| *m.lock().unwrap() += 1)
+//! .run();
+//!
+//! assert_eq!(*m.get_mut().unwrap(), 2);
+//! ```
+//!
+//! Square each number of a vector on a different thread:
+//!
+//! ```
+//! use easy_parallel::Parallel;
+//!
+//! let v = vec![10, 20, 30];
+//!
+//! let squares = Parallel::new()
+//! .each(0..v.len(), |i| v[i] * v[i])
+//! .run();
+//!
+//! assert_eq!(squares, [100, 400, 900]);
+//! ```
+//!
+//! Compute the sum of numbers in an array:
+//!
+//! ```
+//! use easy_parallel::Parallel;
+//!
+//! fn par_sum(v: &[i32]) -> i32 {
+//! const THRESHOLD: usize = 2;
+//!
+//! if v.len() <= THRESHOLD {
+//! v.iter().copied().sum()
+//! } else {
+//! let half = (v.len() + 1) / 2;
+//! let sums = Parallel::new().each(v.chunks(half), par_sum).run();
+//! sums.into_iter().sum()
+//! }
+//! }
+//!
+//! let v = [1, 25, -4, 10, 8];
+//! assert_eq!(par_sum(&v), 40);
+//! ```
+
+#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
+
+use std::fmt;
+use std::iter::{self, FromIterator};
+use std::mem;
+use std::panic;
+use std::process;
+use std::sync::mpsc;
+use std::thread;
+
+/// A builder that runs closures in parallel.
+#[must_use]
+pub struct Parallel<'a, T> {
+ /// Closures to run.
+ closures: Vec<Box<dyn FnOnce() -> T + Send + 'a>>,
+}
+
+impl<'a, T> Parallel<'a, T> {
+ /// Creates a builder for running closures in parallel.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ ///
+ /// let p = Parallel::<()>::new();
+ /// ```
+ pub fn new() -> Parallel<'a, T> {
+ Parallel {
+ closures: Vec::new(),
+ }
+ }
+
+ /// Adds a closure to the list.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ ///
+ /// Parallel::new()
+ /// .add(|| println!("hello from a thread"))
+ /// .run();
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ pub fn add<F>(mut self, f: F) -> Parallel<'a, T>
+ where
+ F: FnOnce() -> T + Send + 'a,
+ T: Send + 'a,
+ {
+ self.closures.push(Box::new(f));
+ self
+ }
+
+ /// Adds a cloned closure for each item in an iterator.
+ ///
+ /// Each clone of the closure takes an item as an argument.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ ///
+ /// Parallel::new()
+ /// .each(0..5, |i| println!("hello from thread #{}", i))
+ /// .run();
+ /// ```
+ pub fn each<A, I, F>(mut self, iter: I, f: F) -> Parallel<'a, T>
+ where
+ I: IntoIterator<Item = A>,
+ F: FnOnce(A) -> T + Clone + Send + 'a,
+ A: Send + 'a,
+ T: Send + 'a,
+ {
+ for t in iter.into_iter() {
+ let f = f.clone();
+ self.closures.push(Box::new(|| f(t)));
+ }
+ self
+ }
+
+ /// Runs each closure on a separate thread and collects their results.
+ ///
+ /// Results are collected in the order in which closures were added. One of the closures always
+ /// runs on the main thread because there is no point in spawning an extra thread for it.
+ ///
+ /// If a closure panics, panicking will resume in the main thread after all threads are joined.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ /// use std::thread;
+ /// use std::time::Duration;
+ ///
+ /// let res = Parallel::new()
+ /// .each(1..=3, |i| 10 * i)
+ /// .add(|| 100)
+ /// .collect::<Vec<_>>();
+ ///
+ /// assert_eq!(res, [10, 20, 30, 100]);
+ /// ```
+ pub fn collect<C>(mut self) -> C
+ where
+ T: Send + 'a,
+ C: FromIterator<T> + Extend<T>,
+ {
+ // Get the last closure.
+ let f = match self.closures.pop() {
+ None => return iter::empty().collect(),
+ Some(f) => f,
+ };
+
+ // Spawn threads, run the last closure on the current thread.
+ let (mut results, r) = self.finish_in::<_, _, C>(f);
+ results.extend(Some(r));
+ results
+ }
+
+ /// Runs each closure on a separate thread and collects their results.
+ ///
+ /// Results are collected in the order in which closures were added. One of the closures always
+ /// runs on the main thread because there is no point in spawning an extra thread for it.
+ ///
+ /// If a closure panics, panicking will resume in the main thread after all threads are joined.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ /// use std::thread;
+ /// use std::time::Duration;
+ ///
+ /// let res = Parallel::new()
+ /// .each(1..=3, |i| 10 * i)
+ /// .add(|| 100)
+ /// .run();
+ ///
+ /// assert_eq!(res, [10, 20, 30, 100]);
+ /// ```
+ pub fn run(self) -> Vec<T>
+ where
+ T: Send + 'a,
+ {
+ self.collect()
+ }
+
+ /// Finishes with a closure to run on the main thread, starts threads, and collects results.
+ ///
+ /// Results are collected in the order in which closures were added.
+ ///
+ /// If a closure panics, panicking will resume in the main thread after all threads are joined.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ /// use std::thread;
+ /// use std::time::Duration;
+ ///
+ /// let (res, ()) = Parallel::new()
+ /// .each(1..=3, |i| 10 * i)
+ /// .finish(|| println!("Waiting for results"));
+ ///
+ /// assert_eq!(res, [10, 20, 30]);
+ /// ```
+ pub fn finish<F, R>(self, f: F) -> (Vec<T>, R)
+ where
+ F: FnOnce() -> R,
+ T: Send + 'a,
+ {
+ self.finish_in::<_, _, Vec<T>>(f)
+ }
+
+ /// Finishes with a closure to run on the main thread, starts threads, and collects results into an
+ /// arbitrary container.
+ ///
+ /// Results are collected in the order in which closures were added.
+ ///
+ /// If a closure panics, panicking will resume in the main thread after all threads are joined.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use easy_parallel::Parallel;
+ /// use std::thread;
+ /// use std::time::Duration;
+ ///
+ /// let (res, ()) = Parallel::new()
+ /// .each(1..=3, |i| 10 * i)
+ /// .finish_in::<_, _, Vec<i32>>(|| println!("Waiting for results"));
+ ///
+ /// assert_eq!(res, [10, 20, 30]);
+ /// ```
+ pub fn finish_in<F, R, C>(self, f: F) -> (C, R)
+ where
+ F: FnOnce() -> R,
+ T: Send + 'a,
+ C: FromIterator<T>,
+ {
+ // Set up a guard that aborts on panic.
+ let guard = NoPanic;
+
+ // Join handles for spawned threads.
+ let mut handles = Vec::new();
+
+ // Channels to collect results from spawned threads.
+ let mut receivers = Vec::new();
+
+ // Spawn a thread for each closure after the first one.
+ for f in self.closures.into_iter() {
+ // Wrap into a closure that sends the result back.
+ let (sender, receiver) = mpsc::channel();
+ let f = move || sender.send(f()).unwrap();
+
+ // Erase the `'a` lifetime.
+ let f: Box<dyn FnOnce() + Send + 'a> = Box::new(f);
+ let f: Box<dyn FnOnce() + Send + 'static> = unsafe { mem::transmute(f) };
+
+ // Spawn a thread for the closure.
+ handles.push(thread::spawn(f));
+ receivers.push(receiver);
+ }
+
+ let mut last_err = None;
+
+ // Run the main closure on the main thread.
+ let res = panic::catch_unwind(panic::AssertUnwindSafe(f));
+
+ // Join threads and save the last panic if there was one.
+ for h in handles {
+ if let Err(err) = h.join() {
+ last_err = Some(err);
+ }
+ }
+
+ // Drop the guard because we may resume a panic now.
+ drop(guard);
+
+ // If a thread has panicked, resume the last collected panic.
+ if let Some(err) = last_err {
+ panic::resume_unwind(err);
+ }
+
+ // Collect the results from threads.
+ let results = receivers.into_iter().map(|r| r.recv().unwrap()).collect();
+
+ // If the main closure panicked, resume its panic.
+ match res {
+ Ok(r) => (results, r),
+ Err(err) => panic::resume_unwind(err),
+ }
+ }
+}
+
+impl<T> fmt::Debug for Parallel<'_, T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Parallel")
+ .field("len", &self.closures.len())
+ .finish()
+ }
+}
+
+impl<T> Default for Parallel<'_, T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Aborts the process if dropped while panicking.
+struct NoPanic;
+
+impl Drop for NoPanic {
+ fn drop(&mut self) {
+ if thread::panicking() {
+ process::abort();
+ }
+ }
+}
diff --git a/tests/smoke.rs b/tests/smoke.rs
new file mode 100644
index 0000000..69db409
--- /dev/null
+++ b/tests/smoke.rs
@@ -0,0 +1,38 @@
+use std::sync::Mutex;
+
+use easy_parallel::Parallel;
+
+#[test]
+fn smoke() {
+ let m = Mutex::new(0);
+ let v = vec![2, 3, 5, 7, 11];
+
+ Parallel::new()
+ .add(|| *m.lock().unwrap() += 10)
+ .add(|| *m.lock().unwrap() += 20)
+ .each(v.iter(), |n| *m.lock().unwrap() += *n)
+ .run();
+
+ assert_eq!(m.into_inner().unwrap(), 10 + 20 + v.iter().sum::<i32>());
+}
+
+#[test]
+fn squares() {
+ let v = vec![10, 20, 30];
+
+ let squares = Parallel::new().each(0..v.len(), |i| v[i] * v[i]).run();
+
+ assert_eq!(squares, [100, 400, 900]);
+}
+
+#[test]
+fn finish() {
+ let v = vec![10, 20, 30];
+
+ let (squares, len) = Parallel::new()
+ .each(0..v.len(), |i| v[i] * v[i])
+ .finish(|| v.len());
+
+ assert_eq!(squares, [100, 400, 900]);
+ assert_eq!(len, 3);
+}