[C #] Parallel of a thread,

Source: Internet
Author: User

[C #] Parallel of a thread,

In some common programming scenarios, using tasks may improve performance. To simplify the process, the static class System. Threading. Tasks. Parallel encapsulates these common situations and uses the Task object internally.

Parallel. &Parallel. Foreach & Pararllel. Invoke
Parallel. for (0, 1000, (I) =>{// I starts from 0 until the end of 1000}); var lst = new List <string> (); Parallel. forEach (lst, (s) =>{// do something}); // Invoke Parallel. invoke () =>{}, () =>{}, () => {});

In three different ways to perform parallel operations, Invoke is a self-defined parallel operation. Like the above Code, only three threads will be opened for execution, there is no difference between For and Foreach and common ones, but it is done in parallel.

Note that the three methods will block the current thread and can be executed only after all the threads are finished. This is useful when data analysis is performed, each piece of data is independent. It makes sense to wait for all threads to finish this process. If you need to avoid thread congestion, you can use the TASK to package a layer, for details, refer to the Task of the [C #] thread. If some threads encounter exceptions during concurrency, the thread will not be interrupted at this time, and aggresponexception will be thrown at the end of all threads (not all exceptions can be captured with this exception ), through this exception, we can know all exceptions:

           Parallel.ForEach(new List<string>            {                "aa",                "bb",                "cc",                "dd",                "ee",            }, (b) =>            {                Thread.Sleep(1000);                throw new Exception(b);            });            }            catch (AggregateException ex)            {                foreach (var exception in ex.Flatten().InnerExceptions)                {                    Console.WriteLine(exception.Message);                }                           }

 

ParallelOptions

Take a look at the official explanation:

  

Public class ParallelOptions {public ParallelOptions (); // cancel the public CancellationToken {get; set ;}// specify the maximum number of work items that can be operated concurrently. public int MaxDegreeOfParallelism {get; set;} // specify the TaskScheduler public TaskScheduler {get; set ;}}

This class provides the setting of the maximum number of concurrent operations, the Token assignment for canceling operations, and the setting of the task scheduler (for this, we need to refer to the previous two topics here)

// Define an object var cancel = new CancellationTokenSource (); var po = new ParallelOptions () {CancellationToken = cancel. token, MaxDegreeOfParallelism = 2,}; // to avoid thread congestion, start a thread Task here. run () => {try {Parallel. for (0, 1000, po, (I) => {Thread. sleep (1000); po. cancellationToken. throwIfCancellationRequested (); Console. writeLine (I) ;});} catch (aggresponexception ex) {foreach (var e in ex. flatten (). innerExceptions) {Console. writeLine (e. message) ;}} catch (Exception ex) {// OperationCanceledException Console. writeLine (ex. getType (). name);} // do not set the canceled TOKEN}, CancellationToken. none); Thread. sleep (10*1000); cancel. cancel ();

The maximum number of Parallel threads is 2. If the number is canceled, all Parallel is canceled and an OperationCanceledException exception is thrown.

Parallel. For & Parallel. Foreach overload

I have selected only one overload.

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

  

Let's take a look at the official explanation:

LocalInit: Local Initialization of a task. It is called once for every task involved in the work. This delegate is called before the task is required to process a work item.

Boy: This delegate is called once for each of the thread locks involved in the work.

LocalFinally: The local termination delegate of a task. This delegate is called once for every task involved in the work. This delegate is called after the task is processed and assigned to all its work items. Even if the subject delegate Code raises an unprocessed exception, it is called.

    

Public static void Parallel_For_Local_Test () {int [] nums = Enumerable. range (0, 1000000 ). toArray <int> (); long total = 0; ParallelLoopResult result = Parallel. for <long> (0, nums. length, () =>{ return 0 ;}, (j, loop, subtotal) =>{ // extend the task time to make it easier to observe the following conclusion Thread. spinWait (200); Console. writeLine ("the current thread ID is: {0}, j is {1}, and subtotal is: {2 }. ", Thread. currentThread. managedThreadId, j. toString (), subtotal. toString (); if (j = 23) loop. break (); if (j> loop. lowestBreakIteration) {Thread. sleep (1, 4000); Console. writeLine ("j is {0}, waiting for 4s, used to determine whether the iteration is enabled and later than the blocking iteration is finished. ", J. toString ();} Console. writeLine ("j is {0}, LowestBreakIteration is: {1}", j. toString (), loop. lowestBreakIteration); subtotal + = nums [j]; return subtotal ;}, (finalResult) => Interlocked. add (ref total, finalResult); Console. writeLine ("total value: {0}", total. toString (); if (result. isCompleted) Console. writeLine ("cyclic execution completed"); else Console. writeLine ("{0}", result. lowestBreakIteration. hasValue? "Break () is called to block the loop.": "Stop () is called to terminate the loop .");}

 

Let's take a look at the output.

Analysis:

A) The generic type parameter TLocal is the data type of the local thread. In this example, it is set to long.

B) The parameter resolution body (j, loop, subtotal) of the three delegates: first, 0 is returned in the initial delegate localInit. Therefore, the initial value of the subtotal parameter in the body delegate is 0, the parameter j of the body Delegate corresponds to the current iteration index. The parameter loop is the ParallelLoopState object of the current iteration state, and the localFinally delegate parameter is the return value of the body Delegate.

C) The three delegates may run concurrently in three phases. Therefore, you must synchronize access to any shared variables. In this example, the System. Threading. Interlocked object is used in the finally delegate.

D) after Break () is called in an iteration with an index of 23:

I. All iterations with an index less than 23 will still run (even if processing is not started) and be processed before exiting the loop.

Ii. iteration with an index greater than 23 will be abandoned if it is not enabled yet; if it is already running, it will be processed before exiting the loop.

E) after Break () is called, accessing the LowestBreakIteration attribute in any loop iteration will return the index corresponding to the iteration that calls Break.

Note: He Yuquan's help

ParallelLoopState

It can be used to make Tasks. Parallel loop iteration interact with other iterations, and provide the function of early exit loop for Parallel class loop. This type of instance should not be created by itself. It is created by the Parallel class and provided to each loop item, and should only be used within the "loop" that provides this instance.

  

Public class ParallelLoopState {// gets whether any iteration of the loop has caused an exception not handled by the corresponding iteration. Public bool IsExceptional {get;} // gets whether ParallelLoopState. Stop () has been called for any iteration of the loop (). Public bool IsStopped {get;} // gets the lowest loop iteration that calls ParallelLoopState. Break () in the Parallel loop. Public long? LowestBreakIteration {get;} // gets whether the current iteration of the loop should exit based on the requests sent by this iteration or other iterations. Public bool ShouldExitCurrentIteration {get;} // other iterations that notify Parallel loop after the current iteration do not need to be run. Public void Break (); // notifies Parallel that all other iterations outside the current iteration do not need to be run. Public void Stop ();}

  

Break ()

Break () is used to notify Parallel loop that other iterations after the current iteration do not need to be run. For example, for a for loop that is iterated from 0 to 1000, if Break () is called in 100th iterations, all iterations lower than 100 will still run (even if processing is not started ), the process is completed before exiting the loop. Iterations not enabled from 101 to 1000 will be abandoned.

For long-running iterations that have been executed, Break () sets the LowestBreakIteration attribute of the ParallelLoopResult structure corresponding to the ParallelLoopResult structure for the LowestBreakIteration attribute to the index of the call Bread () iteration item.

Stop ()

Stop () is used to notify Parallel that all other iterations outside the current iteration do not need to be run, whether they are located above or below the current iteration.

For long running iterations that have been executed, you can check the IsStopped attribute and exit early when it is observed to be true.

Stop is usually used in search-based algorithms. After finding a result, no other iteration is required. (For example, the server that automatically matches the fastest response when watching videos or cartoons)

ShouldExitCurrentIteration attributes

When a loop iteration calls Break or Stop, or an iteration causes an exception, or cancels the loop, the Parallel class will actively attempt to disable other iterations that start to execute the loop. However, other iterations may not be blocked. It may also be that long-running iterations have started to be executed. In this case, iterations can explicitly check the ShouldExitCurrentIteration attribute and stop execution when the attribute returns true.

  

LowestBreakIteration attributes

Return the lowest item that has called the Break method during the process. If the Break method has never been called, null is returned.

 

There is also a fun place, we know Parallel. for & Parallel. foreach returns a ParallelLoopResult object. We can use IsComplete () to determine whether to end the concurrency. However, if we use Break () of ParallelLoopState, IsComplete () the returned value is false, and the LowestBreakIteration attribute is not null. If Stop () is called, IsComplete () returns true, and the LowestBreakIteration attribute is null.

 


What are the differences between the form parameters in C language and the real parameters?

Formal parameters and actual parameters
Function parameters can be divided into form parameters and real parameters. In this section, we will further introduce the characteristics of the form parameters and real parameters and their relationships. Parameters appear in the function definition and can be used in the entire function body. If you leave this function, you cannot use them. Real parameters appear in the main function. After the function is called, the real parameters cannot be used. Parameters and parameters are used for data transmission. When a function is called, the main function transfers the value of the real parameter to the shape parameter of the called function to transmit the data of the called function.
Function parameters and real parameters have the following features:
1. The parameter variable allocates memory units only when called. At the end of the call, the allocated memory units are immediately released. Therefore, the parameter is valid only within the function. After the function call ends, you cannot use this variable after returning the primary function.
2. real parameters can be constants, variables, expressions, functions, etc. No matter what type of real parameters are, they must have a definite value during function calling, in order to pass these values to the form parameter. Therefore, values should be pre-assigned, input, and other methods to obtain a definite value for the real parameter.
3. The number, type, and sequence of the real parameters and form parameters must be strictly consistent; otherwise, the Type Mismatch Error will occur.
4. Data Transmission in function calls is unidirectional. That is, the value of the real parameter can only be transmitted to the form parameter, but the value of the form parameter cannot be reversely transmitted to the real parameter. Therefore, the value of the form parameter changes during the function call process, but the value of the real parameter does not change.

[Example] describes this problem.
Main ()
{
Int n;
Printf ("input number \ n ");
Scanf ("% d", & n );
S (n );
Printf ("n = % d \ n", n );
}
Int s (int n)
{
Int I;
For (I = n-1; I> = 1; I --)
N = n + I;
Printf ("n = % d \ n", n );
}

This program defines a function s, which is used to evaluate the value of Σ ni. Input n value in the main function and use it as a real parameter. The parameter n is transmitted to the s function during the call. (Note that in this example, the object variables and object variables are all named n, but this is two different quantities with different scopes ). In the main function, use the printf statement to output the n value at a time. The n value is the value of the real parameter n. In function s, the printf statement is also used to output an n value, which is the final n value 0 of the form parameter. According to the running status, the input n value is 100. That is, the value of real parameter n is 100. When this value is passed to function s, the initial value of parameter n is also 100. During function execution, the value of parameter n is changed to 5050. After the main function is returned, the value of output parameter n is still 100. It can be seen that the value of the real parameter does not change with the parameter.

What is [C] [U] in English?

C = SEE

U = you

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.