Parallel.For,Parallel.ForEach. Working principle



  • public static ParallelLoopResult For<TLocal>(int fromInclusive, int toExclusive, Func<TLocal> localInit, Func<int, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally);
    

    I've got a few small questions about the above overload, namely:

    1. The Task is created for each cycle iteration for?
    2. First int of entry.

  • QA Engineer

    (1) The issue involves the existence of a specific, documented mechanism for achieving multi-points in this function. How exactly is the discontinuation, the internal details of the implementation.

    Ongoing implementation http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Parallel.cs,1111 type(s)ParallelForReplicatingTaskwho can create http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,6736 ♪ But these classes are internal, and they're inaccessible to the programmer. And, of course, in the next version, implementation has the right to change without warning.

    (2) From https://msdn.microsoft.com/en-us/library/dd783299%28v=vs.110%29.aspx :

    The body delegate is invoked once for each value in the iteration range (from InclusivetoExclusive) It is provided with the following parameters: the iteration count (Int32(a) ParallelLoopState instance that may be used to break out of the loop prematurely, and some local state that may be shared amongst iterations that execute on the same thread.

    I mean, the first parameter is the total number of iterations. It can be used, for example, to understand what part of the overall work has been done.


    Important updatingHow did you notice @Grundy, the meaning of the first parameter in the first place? body - the number of the current iteration, not the number of iterations. Apparently there's a mistake in the documentation. Notice that the numbers can be in a row. For example, such a cycle:

    Parallel.For<string>(
        0, 20,
        () => "Thread #" + Thread.CurrentThread.ManagedThreadId,
        (iter, loopState, localState) =>
            {
                var res = localState + " " + iter;
                Console.WriteLine(res);
                return localState;
            },
        s => { });
    

    I gave it to you:

    Thread #10 0
    Thread #10 1
    Thread #10 3
    Thread #10 4
    Thread #10 5
    Thread #10 6
    Thread #10 7
    Thread #10 8
    Thread #10 9
    Thread #10 10
    Thread #10 11
    Thread #10 12
    Thread #10 13
    Thread #6 2
    Thread #6 16
    Thread #6 17
    Thread #6 18
    Thread #6 19
    Thread #10 15
    Thread #11 14
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2