Caladin00
Caladin00

Reputation: 356

How would I apply Cilk Plus Extensions to this simple C++ code?

So I've been tasked with finding a way to parallelize this simple C++ problem below. I've already had OpenMP explained to me (on a separate question) as one possible method and it was very solid. That being said, Clik Plus extensions appear to be minimally invasive to existing C++ code and I would greatly appreciate if someone could show + give me a detailed explanation on how Clik Plus might be tied into and parallelize this code. The steps of the existing code are shown below.

1) take a positive integer N as an argument

2) create an integer array of size N

3) populate the integers from range [1,1000]

4) Find the largest integer and the sum of the array in parallel

5) print the largest integer and the sum of the array.

Step 4 is the step that I need to implement Clik Plus to.

As it stands, my code works fine, but it isn't parallelized. I understand that there are three keywords provided by Clik Plus:

cilk_for - Parallelize for loops

cilk_spawn - Specifies that a function can execute in parallel with the remainder of the calling function

cilk_sync - Specifies that all spawned calls in a function must complete before execution continues

My problem is I don't know where/how to implement them in my code.

#include  <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){

cout << "Enter the Size of the Array (N):  \n ";
int N;
cin >> N;

int array[N];
int largest_number = 0;
int sum = 0;

srand(time(0));
cout << "Populating Array...\n";

//  Filling up the Array  with values
for(int i =0; i < N; i++)
{

array[i] =  (rand() % 1000) + 1;

}


// Finding the largest value and calculating sum of the array
for( int j  = 0; j < N; j++)
{

sum += array[j];

if( array[j] > largest_number)
{largest_number = array[j];}

}

cout << "Output: \n";
cout << "Maximum:  " <<  largest_number << ";" <<  "Sum: " <<  sum;
cout << "\n";

}

At the end I should be able to compile this code with the command g++ main.cpp -fclikplus and have it run as defined by the 5 steps above.

Thank you!

Upvotes: 0

Views: 176

Answers (0)

Related Questions