Parallel Arrays C++ Example



Back to: C#.NET Tutorials For Beginners and Professionals

Multidimensional arrays can be described as 'arrays of arrays'. For example, a bidimensional array can be imagined as a two-dimensional table made of elements, all of them of a same uniform data type. Jimmy represents a bidimensional array of 3 per 5 elements of type int. The C syntax for this is. In this tutorial, you will learn to work with arrays. You will learn to declare, initialize and access array elements of an array with the help of examples. An array is a variable that can store multiple values. OpenMP (www.openmp.org) makes writing the Multithreading code in C/C so easy. OpenMP is cross-platform can normally ben seen as an extenstion to the C/C, Fortran Compiler i.e. OpenMP hooks the compiler so that you can use the specification for a set of compiler directives, library routines, and environment variables in order to specify shared memory parallelism. For example, one might declare an array of 100 names, each a string, and 100 ages, each an integer, associating each name with the age that has the same index. An example in C using parallel arrays.

Parallel Foreach in C#

Arrays

In this article, I am going to discuss the Parallel Foreach in C# with some examples. As we already discussed in our previous article that the Task Parallel Library (TPL) provides two methods (i.e. Parallel.For and Parallel.Foreach) which are conceptually the “for” and “for each” loops, except that, they use multiple threads to execute multiple iterations at the same time on a machine with multiple cores. In our previous article, we already discussed the Parallel for Method in C#with examples. Here, in this article, I am going to keep the focus on Parallel Foreach method in C#.

At start of parallel region master creates team of parallel ”worker” threads (FORK) Statements in parallel block are executed in parallel by every thread At end of parallel region, all threads synchronize, and join master thread (JOIN) Implicit barrier. Will discuss synchronization later F O R K J O I N Thread #3 Thread #0 Thread #2 Thread #1.

Parallel.ForEach in C#

The Parallel ForEach in C# provides a parallel version of the standard, sequential Foreach loop. In standard Foreach loop, each iteration processes a single item from the collection and will process all the items one by one only. However, the Parallel Foreach method executes multiple iterations at the same time on different processors or processor cores. This may open the possibility of synchronization problems. So, the loop is ideally suited to processes where each iteration is independent of the others.

Note: We need to use the parallel loops such as Parallel.For and Parallel.ForEach method to speed up operations where an expensive, independent operation needs to be performed for each input of a sequence.

A sequential Foreach loop in C#:

A parallel Foreach loop in C#:

The parallel version of the loop uses the static ForEach method of the Parallel class. There are many overloaded versions available for this method. This is the simplest overloaded version which accepts two arguments. The first one is the collection of objects that will be enumerated. This can be any collection that implements IEnumerable<T>.

The second parameter accepts an Action delegate, usually expressed as a lambda expression which determines the action to take for each item in the collection. The delegate’s parameter contains the item from the collection that is to be processed during the iteration.

C# Parallel Foreach Method Example.

Let us understand Parallel Foreach with an example. First, we will write an example using the standard sequential Foreach loop and will see how much time it will take to complete the execution. Then we will write the same example using the Parallel ForEach method and will see how much time it will take to complete the execution of the same example.

In the below example, we create a sequential Foreach loop that performs a long-running task once for each item in the collection. The code below loops through a list of ten integers generated using the Enumerable.Range method. In each iteration, the DoSomeIndependentTimeconsumingTask method is called. The DoSomeIndependentTimeconsumingTask method performs a calculation that is included to generate a long enough pause to see the performance improvement of the parallel version.

Now run the application and observe the output.

As you can see from the above output screen the “Foreach” loop statement took approximately 3035 milliseconds to complete the execution.

Let’s rewrite the same example using the C# Parallel ForEach method.
Arrays in c++ examples

Now, run the application and see the output as shown below. The time may vary on your machine.

As you can see in the above output, the Parallel.ForEach method took 1419 milliseconds to complete the execution.

The Degree of Parallelism:

Using the Degree of Parallelism we can specify the maximum number of threads to be used to execute the program. The syntax to use the Degree of Parallelism is given below.

The MaxDegreeOfParallelism property affects the number of concurrent operations run by Parallel method calls that are passed this ParallelOptions instance. A positive property value limits the number of concurrent operations to the set value. If it is -1, there is no limit on the number of concurrently running operations.

By default, For and ForEach will utilize however many threads the underlying scheduler provides, so changing MaxDegreeOfParallelism from the default only limits how many concurrent tasks will be used.

Let us see an example for better understanding.

Now run the above code above multiple times, and definitely, you will get different output. You will also observe that the number of threads is created is not in our control. Now, let us see how to restrict the number of threads to be created.

How to control the degree of concurrency i.e. How to restrict the number of threads to be created?

We can restrict the number of concurrent threads created during the execution of parallel loops by using the MaxDegreeOfParallelism property. By assigning some value to MaxDegreeOfParallelism, we can restrict the degree of this concurrency and can restrict the number of processor cores to be used by our loops. The default value of this property is -1, which means there is no restriction on concurrently running operations.

Let’s see the example.

In the above code, we are setting the MaxDegreeOfParallelism to 2, which means that only a maximum of 2 threads will be created, that will, in turn, use fewer cores, which is 2 here. Now run the application and see the output as shown below.

Whatever number of times we execute the above code, the number of threads will never go above 2.

In the next article, I am going to discuss the Parallel Invoke Method in C# with some examples. Here, in this article, I try to explain the Parallel ForEach in C# with some examples. I hope you understood the need and use of C# Parallel.Foreach method.

  • C Programming Tutorial
  • C Programming useful Resources
  • Selected Reading

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Parallel

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Parallel Arrays C++ Example

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows −

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −

The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −

When the above code is compiled and executed, it produces the following result −

Arrays in Detail

Parallel arrays c++ examples

Parallel Arrays C++ Examples

Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −

Java Parallel Arrays

Sr.No.Concept & Description
1Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

2Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name without an index.

3Return array from a function

C allows a function to return an array.

4Pointer to an array

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.