Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure grain size is >= 1 & reduce duplication in parallelFor. #43

Merged
merged 1 commit into from
May 31, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public class NonBlockingThreadPool<Environment: ConcurrencyPlatform>: ComputeThr

/// Executes `fn`, optionally in parallel, spanning the range `0..<n`.
public func parallelFor(n: Int, _ fn: VectorizedParallelForBody) {
let grainSize = n / maxParallelism // TODO: Make adaptive!
let grainSize = max(n / maxParallelism, 1) // TODO: Make adaptive!

func executeParallelFor(_ start: Int, _ end: Int) {
if start + grainSize >= end {
Expand All @@ -309,20 +309,20 @@ public class NonBlockingThreadPool<Environment: ConcurrencyPlatform>: ComputeThr

/// Executes `fn`, optionally in parallel, spanning the range `0..<n`.
public func parallelFor(n: Int, _ fn: ThrowingVectorizedParallelForBody) throws {
let grainSize = n / maxParallelism // TODO: Make adaptive!
var err: Error? = nil
let lock = Environment.Mutex()

func executeParallelFor(_ start: Int, _ end: Int) throws {
if start + grainSize >= end {
try fn(start, end, n)
} else {
// Divide into 2 & recurse.
let rangeSize = end - start
let midPoint = start + (rangeSize / 2)
try self.join({ try executeParallelFor(start, midPoint) }, { try executeParallelFor(midPoint, end) })
parallelFor(n: n) { start, end, total in
do {
try fn(start, end, total)
} catch {
lock.lock()
defer { lock.unlock() }
err = error
}
}

try executeParallelFor(0, n)
if let err = err { throw err }
}

/// Requests that all threads in the threadpool exit and cleans up their associated resources.
Expand Down