From 7cced98dd282c3b21b83f9383d47e00e82d1dd12 Mon Sep 17 00:00:00 2001 From: Christoph Ruegg Date: Mon, 10 Oct 2011 00:20:05 +0200 Subject: [PATCH] Threading: CommonParallel now supports empty loops. Closes gh-19. CommonParallel did break on empty loops with an argument exception instead of just doing nothing. It now exits early if there's nothing to do in For and Invoke, no longer throwing an exception. Also, it now special cases single-element iterations and inlines their execution (trivial loop unrolling), skipping all the threading/task overhead. --- src/Numerics/Threading/CommonParallel.cs | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/Numerics/Threading/CommonParallel.cs b/src/Numerics/Threading/CommonParallel.cs index 7ce9ce15..25a45d8b 100644 --- a/src/Numerics/Threading/CommonParallel.cs +++ b/src/Numerics/Threading/CommonParallel.cs @@ -72,6 +72,20 @@ namespace MathNet.Numerics.Threading /// At least one invocation of the body threw an exception. public static void For(int fromInclusive, int toExclusive, Action body, bool parallel) { + // Special case: no action + if (fromInclusive >= toExclusive) + { + return; + } + + // Special case: single action, inline + if (fromInclusive == (toExclusive - 1)) + { + body(fromInclusive); + return; + } + + // Common case if (parallel) { #if SILVERLIGHT @@ -353,6 +367,20 @@ namespace MathNet.Numerics.Threading /// An action threw an exception. public static void Invoke(params Action[] actions) { + // Special case: no action + if (actions.Length == 0) + { + return; + } + + // Special case: single action, inline + if (actions.Length == 1) + { + actions[0](); + return; + } + + // Common case var maxThreads = Control.DisableParallelization ? 1 : Control.NumberOfParallelWorkerThreads; #if SILVERLIGHT Parallel.Invoke(actions);